* Note: I use windows, so EOF for me is ctrl + Z.
For a while, I noticed that the EOF input behaves differently in isolation than when using another input. For example, ^Z (the EOF command for windows on the command line) and a^Z seem to cause different behavior in the following code:
#include <stdio.h> #define MAX 1000 int getline(char s[]); main() { int line; char arr[MAX]; while( (line = getline(arr)) != EOF) printf("%s",arr); system("Pause"); return 0; } int getline(char s[]) { int c, i = 0; while ((c = getchar()) != EOF && c != '\n') { s[i++] = c; } if (c == '\n') { s[i++] = c; } else return EOF; s[i] = '\0'; return 1; }
If I type ^Z + at the command line, the program will confidently switch to system("Pause"); However, if I type abc^Z + enter, nothing will happen, as if EOF was ignored and the command '\n' never received. If at this moment I press the key again, it shows the following:

I have been doing this debugging and debugging this code and its small variants for more than an hour and canβt find anything wrong with that. Theoretically, if I type abc^Z + enter, I expect the input to be interpreted as abcEOF\n , which will give:
s[0] = 'a' s[1] = 'b' s[2] = 'c' i = 3 when loop breaks from c = EOF if (c == '\n') skipped since c = EOF leads to else -> return EOF in main(), line = EOF since that is what the function getline returned while loop breaks because of above system("Pause"); follows
Is there something wrong with my code that I am missing, or is there some kind of quirk for EOF or the command line that I should be aware of? I am pretty sure that this is not the only case where mixing ^Z with other values ββcaused unintended behavior.
source share