Reputation: 46
I was trying to make a code that gets only an integer as input. I found a working solution here
int n, input, temp, status;
printf("Height:");
status = scanf("%d",&n);
while(status!=1)
{
while((temp=getchar()) != EOF && temp != '\n');
printf("Height:");
status = scanf("%d", &n);
}
I want to know what exactly makes this part work and what are those "extra hidden characters"
while((temp=getchar()) != EOF && temp != '\n');
Can anyone explain, please?
Upvotes: 1
Views: 193
Reputation: 51423
while((temp=getchar()) != EOF && temp != '\n');
First, you need to understand what getchar function does, namely:
The C library function int getchar(void) gets a character (an unsigned char) from stdin.
Return Value This function returns the character read as an unsigned char cast to an int or > EOF on end of file or error.
When the user types something that will be picked by the scanf
, the user press an [enter]
which will send a "\n". That newline will not be read by the scanf
function but rather stay on the input buffer. The EOF
is for the case that someone explicitly closes the stream, for instance pressing CTRL-Z. So the code:
while(status!=1)
{
while((temp=getchar()) != EOF && temp != '\n');
printf("Height:");
status = scanf("%d", &n);
}
check first the returning type value of the scanf which:
Return Value On success, the function returns the number of items of the argument list successfully read. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror) and, if either happens before any data could be successfully read, EOF is returned.
In your case, you expect to read a single numerical value (i.e., status = scanf("%d",&n);
). The remains of the loop is basically asking for the user to provide a valid input (i.e., a numeric value), which consequently leads to status
being 1
, and the exit of the outermost while loop.
Upvotes: 3
Reputation: 409166
If a user enters some non-numeric input (for example foo
instead of an integer) then scanf
will return 0
and leave the non-numeric input in the input buffer.
So the next time you call scanf
it will attempt to read the exact same non-numeric input and fail again.
The loop
while((temp=getchar()) != EOF && temp != '\n');
will read character by character until either it comes to and end of file, or the character is a newline. The characters the loop reads will be ignored and thrown away.
This is a way to skip all the non-numeric input that the user might have entered.
Upvotes: 1
Reputation: 711
The EOF character is received when there is no more input. The name makes more sense in the case where the input is being read from a real file, rather than user input (which is a special case of a file). This means that your loop will break when you receive an EOF or if the user hits enter, in this case, you receive a '\n'.
Upvotes: 0