Reputation: 37
As read in this answer:
num
will always contain an integer because it's anint
. The real problem with your code is that you don't check thescanf
return value.scanf
returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and thenum
variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by
scanf("%d\n")
, but here's a trick to do it:int num; char term; if(scanf("%d%c", &num, &term) != 2 || term != '\n') printf("failure\n"); else printf("valid integer followed by enter key");
I saw this post works perfectly, but it does not work inside a do-while loop. I need to get from user until the correct input but when the loop is executed first, it so on continuously printing the failure without getting from user.
What is the problem?
Upvotes: 0
Views: 3686
Reputation: 148910
The problem is that the offending characters are not cleared from the input buffer. If you want to clear until the first end of line after an error, you have to do it explicitely:
int num;
char term;
for (;;) {
if(scanf("%d%c", &num, &term) != 2 || term != '\n') {
printf("failure\n");
int c;
while (('\n' != (c=fgetc(stdin))) && (c != EOF)); // clear up to end of line
if (c == EOF) break; // do not read past EOF...
}
else {
printf("valid integer followed by enter key");
break;
}
}
Upvotes: 1