0

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?

3
  • "a=%lf , b=%lf , c=%lf" Allowing for white-sapce characters means your format string must have them. Commented Nov 13, 2016 at 10:44
  • 2
    Your condition is also wrong, I wager. scanf returns how many items from the format specifiers it read successfully. So to check for success, you'd need to check it returns 3. Commented Nov 13, 2016 at 10:48
  • Deja vous - stackoverflow.com/questions/40572652/… Commented Nov 13, 2016 at 11:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.