Reputation: 145
I would like to allow the user to only put input in a specific format.
The format:
a=1,b=-2,c=3
for example. Spaces are allowed inbetween the commas and the characters.
I'm using: if (scanf("a=%lf,b=%lf,c=%lf",&a,&b,&c) == 1)
but for some reason it doesn't work. How can I fix it?
Upvotes: 0
Views: 348
Reputation: 144550
You are converting 3 numbers, the return value should be 3 if all conversions are successful. Also note that %lf
ignores spaces before the number. If you also want to ignore spaces around the ,
and before the =
or the a
, add a space in the format string:
double a, b, c;
if (scanf(" a =%lf , b =%lf , c =%lf", &a, &b, &c) == 3) {
/* conversion was successful, 3 numbers parsed */
...
}
Note however that scanf()
will not ignore just space characters, it will ignore and whitespace characters, including newlines, tabs, etc.
Upvotes: 1
Reputation: 324
From the documentation on scanf
If successful, the total number of characters written is returned, otherwise a negative number is returned.
Try
if (scanf("a=%lf , b=%lf , c=%lf",&a,&b,&c)==3)
You must include empty spaces in the string scanf takes as an argument, specifying the format.
Upvotes: 1