Confirm input type in do-while loop C
Basically, I need to make sure that the input is an integer , for example:
do {
printf("Enter > ");
scanf("%d", &integer);
} while (/* user entered a char instead of an int */);
I tried various methods, but always got a runtime error or an infinite loop when I tried to type char. I knew that fflush(stdin)this is undefined behavior that it is better not to include in my code to prevent any error, plus it no longer works in VS2015 for some reason.
Below are the codes I 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);
Anyway, except fflush(stdin)which can be used to prevent an infinite loop when the user is typing charin C ?
thank
, "scanf()" . , " ".
, scanf(). , ... scanf "0", ... , - .
:
#include <stdio.h>
void discard_junk ()
{
char c;
while((c = getchar()) != '\n' && c != EOF)
;
}
int main (int argc, char *argv[])
{
int integer, i;
do {
printf("Enter > ");
i = scanf("%d", &integer);
if (i == 1) {
printf ("Good value: %d\n", integer);
}
else {
printf ("BAD VALUE, i=%i!\n", i);
discard_junk ();
}
} while (i != 1);
return 0;
}
:
Enter > A
BAD VALUE, i=0!
Enter > B
BAD VALUE, i=0!
Enter > 1
Good value: 1
', !