I have a program that accept orders by reading commands from a file.
In this file some commands are “float string”, like “1.0”,”2.0″, but they are invalid, what the program need is integer, like “1”,”2″. So, how can I make the program understand the commands like “1.0” is invalid? Is there any neat way to do this?
char buf[CMDSIZE];
if(fgets(buf, CMDSIZE, stdin)) //buf likes this: "1.0 \n"
{
*prio = 1; *command = -1; *ratio =1.0;
// I need to make sure that command is not "1.0" or something like this
sscanf(buf, "%d", command);
switch(*command){....blahblah......}
}
Thank you.
It’s easier to use
strtol.This will parse a base-10 integer. The pointer
ewill point to the first character after the integer. You can check to make sure it’s a NUL byte and signal an error otherwise. (You also have to check that the input isn’t empty.)If you want to allow spaces / newlines after the number, you can do that too. Note that
strtoleats leading whitespace — but not trailing whitespace.Footnote: Checking for overflow and underflow with
strtolis a little weird. You have to seterrnoto 0 first, callstrtol, then check if the result isLONG_MINorLONG_MAXand iferrnois set toERANGE.