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?
2 Answers
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.
Comments
From the documentation on scanf
Return value
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.
"a=%lf , b=%lf , c=%lf"Allowing for white-sapce characters means your format string must have them.scanfreturns how many items from the format specifiers it read successfully. So to check for success, you'd need to check it returns3.