Reputation: 109
I have read in an earlier discussion that
#include <stdio.h>
int main ()
{
int num;
printf("\nPlease enter an integer:\n");
scanf("%d",&num);
// Let us check whether the user input is in integer //
while ((num = getchar()) != '\n' && num != EOF)
{
printf("\n\nError in input\n");
printf("Please enter valid integer\n");
scanf("%d",&num);
}
}
will check whether the input is an integer or not. The code works. But I do not understand what
while ((num = getchar()) != '\n' && num != EOF)
is doing. Can anyone help?
Upvotes: 0
Views: 263
Reputation: 213832
while ((num = getchar()) != '\n' && num != EOF)
is just a needlessly obfuscated way of writing:
num = getchar();
while((num != '\n') && (num != EOF)) // inner parenthesis not necessary, just for readability
{
...
num = getchar();
}
Upvotes: 1
Reputation: 23802
scanf("%d",&num);
will parse the integer present in stdin
buffer if it is indeed parseable, characters that are not parseable will remain in the buffer.
The trick in this code is to check, after the scanf
, if the character present in the buffer is a newline (\n
), if it is, the value was parsed correctly, in that case the loop asking for new input will not be executed, if not, the non parsed character will still be in the buffer, will be read by getchar
which will verify that indeed it's not \n
, and the cycle will be executed.
The problem with this is that if you input something like "aadd"
the cycle will execute 4 times, the number of characters that remained in the input buffer.
Though it, more or less works, it's not the best method, as stated in the comments, it's best to read the line from the buffer with something like fgets
, parse it, for example, with sscanf
or strtol
and if it fails, ask for new input.
Upvotes: 1