Reputation: 2105
I'm trying to match my input with 3 variable types: an integer, a float and a string.
char *input = "1 5.456 oxygen\0";
int i = sscanf(input, "%d %f %[^\0]", &id, &dens, name);
if (i != 3)
break;
This works great if input does contain all these 3 types and I use the value returned by sscanf in order to check this.
But if input is missing the integer at the beginning such as:
char *input = " 5.456 oxygen\0";
the variable i will still be equal to 3 because sscanf will match id with 5 and dens with .456.
What is the best way to use sscanf so it checks for whitespaces between the required types (at least one or more whitespaces).
Upvotes: 1
Views: 97
Reputation: 87321
const char *input = "1 5.456 oxygen";
char c1, c2;
if (sscanf(input, "%d%c%f%c %[^\n]", &id, &c1, &dens, &c2, name) != 5 ||
!isspace(c1) || !isspace(c2)) break;
Please note that it's impossible to insert a \0
to the scanf format, so you need something else, e.g. \n
there. This works if the input doesn't contain a \n
.
Upvotes: 1