-1

As practice, I'm trying to make a simple fake shell with 2 simple commands. it is also my first time using strtok. it takes a command(get or set) and a parameter to access(width, height, etc.). my problem is the third argument is a float and I'm wanting to convert it from the char * that strtok returns to the float variable that I'm trying to store it in. I'm at a loss at the moment. I used to be pretty efficient at c, but after a few years of taking a break, I'm amazed at how much of the language I've forgotten. Any help would be much appreciated. I'm not home at the moment, but if I need to I will post the code.

Thank you for your time.

dhott
  • 19
  • 1

2 Answers2

1

Maybe atof is what you're looking for? Takes a char* (from strtok for example) and turns it into a double.

jpw
  • 44,361
  • 6
  • 66
  • 86
  • Wow, thank you so much. Very quick response. Any way I can +1 you. New to this site, not used to the workings, but thank you again. I was about to beat my head against the wall – dhott Aug 04 '13 at 18:47
  • 1
    @Toxor You can, and should, accept the answer that best solves your problem. In this case the answer given by Vadim is more complete than the one I gave so you should accept his answer. When, and if, you gain more reputation in the future you can upvote helpful answers. – jpw Aug 04 '13 at 18:59
1

To parse Double, your options are -

  1. strtod() - see here or here

  2. atof() - see here

  3. sscanf() - see here

atof does not allow to validate the number, it'll return 0.0 if parsing fails. sscanf is a bit cumbersome and the %f formatting may not be present on all systems. Try looking at strtod or strtof (if you want floats).

You could use it like this (txt is your char*)

char *end;
float num = strtof(txt, &end);
if (end != txt + strlen(txt))
{
    // This means something went wrong
}
else
{        
    // This means everything is OK
}
Vadim
  • 2,847
  • 15
  • 18
  • Tank you as well. I think the strtof will better fit the purpose – dhott Aug 04 '13 at 19:00
  • The error checking is not good. `if (end != txt)` does **not** mean everything went fine. You should use `if (end == txt + strlen(txt))` instead. –  Aug 04 '13 at 19:08
  • All right, Now my gdb wont run on kubuntu. What is going on. I keep catching a sigsev and cant run gdb to figure it out. How do I post code? – dhott Aug 05 '13 at 00:38