1

This is my code example. I wrote the question in my comment:

main(){
    long cnt; // chars count
    int c;

    /* Why the 'for' cicle doesn't finish when I input the
     * "a^Z" string and press ENTER? At this case '^Z' is
     * CTRL + Z (i.e this is EOF). I expected the second loop
     * will get the EOF (i.e. -1), but it has 26 instead of. Why?
     */
    for(cnt = 0; (c = getchar()) != EOF; ++cnt)
        ;

    printf("Chars count: %ld", cnt);
}

If I put a, ENTER, CTRL + Z, ENTER then I get the expected result: the CTRL + Z breaks the loop.

UPD

When I read info about getchar function then I saw that it uses the line-buffered input. It expects ENTER for pushing the data. I didn't see info that it also can push data when it get the Ctrl - Z. Therefore I expected that the second value will be EOF in my case (and the loop will be broken), i.e. I expectet that my string line will be parsed like the a, EOF, \n sequence.

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

1 Answers1

1

When you press a+ CTRL + Z and then press ENTER, the CTRL + Z flushes the input (stdin) and the next input is \n, which is not an EOF. You need to press CTRL + Z twice to simulate the second EOF.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261