Basically, I need to ensure that input is an integer, like so:
do {
printf("Enter > ");
scanf("%d", &integer);
} while (/* user entered a char instead of an int */);
I have tried various methods, but it always end up with run-time error or infinite loop when I tried to enter a char
. I have knew that fflush(stdin)
is an undefined behavior, which is better not to involve it in my code in order to prevent any error plus it no longer works in VS2015 due to some reasons.
The codes below are the method that I have tried:
typedef enum {false, true} bool;
int ipt;
char c;
bool wrong_ipt;
do {
c = '\0';
printf("Enter > ");
scanf("%d%c", &ipt, &c); //infinite loop occurs while a char has been entered
} while (c != '\n');
do {
c = '\0';
printf("Enter > ");
} while (scanf("%d", &ipt) != EOF);
do {
wrong_ipt = false;
do {
ipt = NULL;
printf("Enter > ");
scanf("%d", &ipt);
if (ipt == NULL) {
wrong_ipt = true;
break;
}
} while (ipt == NULL);
} while (wrong_ipt);
Is there anyway other than fflush(stdin)
which can be used to prevent the infinite loop when user entered a char
in C?
Thank you
The problem is that "scanf()" can leave unread data in your input buffer. Hence the "infinite loop".
Another issue is that you should validate the return value from
scanf()
. If you expect one integer value ... and scanf returns "0" items read ... then you know something went wrong.Here is an example:
Sample output:
'Hope that helps!
Your fundamental mistake is that you never tell your program to consume the invalid input. In words, you told the program:
I assume what you thought you were doing was
So what you need to do is to rewrite your code so it does what you meant to do (or come up with some other approach, as in the other answer). That is, write your program to:
Some relevant functions you may find useful are
fgets
,sscanf
, andatoi
. (also, try to resist the temptation to write buggy code; e.g. if you intend to read a line of input, make sure you actually do so, and correctly. Many people are lazy and will do the wrong thing if the line is long; e.g. just read part of the line, or cause a buffer overflow)The format specifier %d tells to
scanf
that an integer value is expected in the command line. When the user enters a line of data, it's read as a string, and thenscanf
attempts to understand if the entered string can be interpreted as the decimal digits of an integer number.If this interpretation succeds, then the value thus found is stored in the integer variable you passed as argument.
The number of rigth replacements done by
scanf
are retrieved by that function in the form of anint
value. Since you expect only one input, the value 1 will indicates that everything was fine.So, if there was an error, as for example, the user entered a non-valid integer number, the number returnd by
scanf
is less than the number of format specifiers. In this case, a value less than 1 informs that an error happened: