Why does the program enter infinite loop when I input EOF (Ctrl-D)?
#include <stdio.h>
main()
{
int c = EOF ;
while(c==EOF)
{
printf("input value c=%d \n",c);
printf("EOF=%d \n",EOF);
c = getchar(); //expect the while loop to pause here and wait for input
}
printf("the value of last input c=%d \n",c);
}
When I enter any other character the program exits immediately as expected. But when I enter EOF (Ctrl-D) I expect the program to reiterate within the while loop and wait for the next user input with getchar.
Update: I read the manual pages for the shell this program runs in manpage for GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)
Commands for Changing Text
end-of-file (usually C-d)
The character indicating end-of-file as set, for example, by ``stty''. If this character is read
when there are no characters on the line, and point is at the beginning of the line, Readline inter‐
prets it as the end of input and returns EOF.
I think what is happening is that when I enter EOF as input the shell no longer passes input to program so program just skips the line c=getchar(); and repeats the loop. Any further insights will be appreciated.
clearerr(stdin);at the start of your loop? I can't reproduce your problem (on Windows) but maybe, on your platform, the EOF flag preventsgetcharfrom attempting further input operations.getcharreturnsEOF[from enteringctrl-D], it will continue to do so. Aftergetchar[as Adrian suggested], if you do:if (c == EOF) clearerr(stdin);, it will work as you're intending: if you then enterj\n[you need the newline to get the kernel tty layer to send the chars], you'll get thej. It is not the shell that is controlling input, it is the kernel tty driver/layer. But, why? The usual is:while (1) { c = getchar(); if (c == EOF) break; process_char(c); }EOFreturned due to input error, a subsequent call may not returnEOF- depends on the error.while ((c = getchar()) != EOF) { … }with no need forgetchar()inside the loop. That doesn't do quite the same job, but it is probably more useful in the long run.