February 12th, 2013, 01:17 PM
Error checking scanf
i have to use scanf to make a math equation
i have to use the return type to error check it
scanf always returns the correct amount of variables entered
even if i try to enter the wrong amount of variables
if i enter 1 variable and i need 3, after i press enter, it is still scanning and waits for 2 more variables
even if i enter 4 or more variables, scanf still returns "valid expression"
int precision, numVars;
double a, b;
numVars=scanf("%lf %c %lf", &a, &c, &b);
February 12th, 2013, 01:48 PM
Yes, that's correct and exactly what we would expect.
Originally Posted by chopficaro
You told scanf to read three arguments and you supplied it with three arguments, so it's satisfied. In fact, it stopped reading from the input buffer as soon as it had found that third valid argument. That means that the extra arguments you had entered are still in the input buffer. When you call scanf again, it will immediately start with that fourth argument, that extra one, that you had entered.
That is how scanf works.
February 12th, 2013, 01:50 PM
You've described how scanf works.
All whitespace (including newlines) are the same to scanf.
So whether you type in
1 + 2
it's all the same to scanf.
If you want to make a line the unit of input, then you need to use fgets() and sscanf.
Oh, and main returns int, not void.
numVars=sscanf("%lf %c %lf", &a, &c, &b);
March 20th, 2013, 12:59 PM
im not allowed to use fgets i am only allowed to use scanf
March 20th, 2013, 01:10 PM
OK, so break that single scanf up into separate scanf's. That way, you can check the return value of each one for being valid. Just be sure to leave a space in front of the character input (ie, " %c") so that it doesn't just read in the space character or newline.
Seems kind of odd that your homework assignment would still not be due more than a month later.
is an infinite loop. Your program will never end on its own. You will need to Ctrl-C out of it or worse.