It’s a basic question.. but had to ask. For a program like this, if the use case is 123^Z, the program doesnt terminate, even though i put an EOF at the end (Ctrl+Z). Why is that so? It’s only when I put an EOF after a CR that it works. Any anwers will be appreciated. Thanks.
#include < stdio.h>
void main()
{
int i, nc;
nc = 0;
i = getchar();
while (i != EOF) {
nc = nc + 1;
i = getchar();
}
printf("Number of characters in file = %d\n", nc);
}
In Windows, the Ctrl-Z shortcut will only take effect if it’s pressed at the start of a line. Otherwise, the OS ignores it. You must press “enter” or “return” to insert a newline character first.
In Unix, the Ctrl-D shortcut will flush
stdinimmediately (as mentioned in the below comments), but will not causegetchar()to returnEOFunless you are on a new, blank line; same as in Windows.From the comments (below):
This addresses a good point – no file actually contains
EOF– and pressing Ctrl-D won’t “insert” (as I had previously said) anything into thestdinstream. It just flushesstdin.EOFis a standard macro representing a notification that the end of the file was reached by a standard function.Thanks to @R. for the explanation about
EOF.