Reputation: 9940
I am learning C from ' programming in C' by Stephen Kochan. I am working on exercise no 4 of chapter 6 , writing a code that acts as a simple accumulator calculator. code is following. it works fine as long as inputs are provided in the right manner order.
#include<stdio.h>
int main(void)
{
float num, accum = 0;
char operator;
while(1)
{
printf("Enter the number and the operator ");
scanf("%f %c",&num, &operator);
if (operator == 'E') break;
switch (operator){
case 'S':
accum = num;
printf("= %g\n",accum);
break;
case '+':
accum = accum + num;
printf("= %g\n",accum);
break;
case '-':
accum = accum - num;
printf("= %g\n",accum);
break;
case '*':
accum = accum * num;
printf("= %g\n",accum);
break;
case '/':
accum = accum / num;
printf("= %g\n",accum);
break;
}
}
printf("= %g\n",accum);
printf("End of Calculation\n");
return 0;
}
but it hangs on the wrong inputs. what can be done to check such behaviour?
Upvotes: 0
Views: 221
Reputation: 186108
scanf()
returns 2, indicating that it has populated both argumentsFor increased robustness, you might want to read the whole line using fgets()
(don't use gets()
because it is vulnerable to buffer overflow) and parse the result using sscanf()
. This is only necessary if you want to provide recovery from bad inputs. Otherwise, just stick with scanf()
and exit(1)
(and an error message) if anything goes wrong.
Upvotes: 2
Reputation: 61457
The short version is "don't use scanf()
."
The problem is that scanf()
provides only a limited indication of error, and leaves the erroneous data unread tp be picked up by the next call; especially if you're not bothering to do error checking, it's just going to spin forever on the bad data.
fgets()
or similar to read an entire line, and sscanf()
to parse from the line.Upvotes: 6
Reputation: 28595
Dont use scanf
. Thats the first sight suggestion for this program. Use something like getchar
like shown here They are dealing with the same problem as yours.
Upvotes: 2