-1

I've code:

int c;
while((c = getchar()) != EOF)
    putchar(c);

As I know EOF is equal to -1 I read -1 from keyboard(input stream) and it must stop itself,but loop keeps repeating. why?

Higgs
  • 63
  • 2
  • 8
  • 6
    Try using Ctrl+d or Ctrl+Z – Sourav Kanta Jun 24 '15 at 16:25
  • 1
    If you mean you're typing the two characters `-1` then it won't stop (the characters will just be echoed. EOF is signalled by the end of the file: either `Ctrl-Z` (Windows) or `Ctrl-D` (Unix). – TripeHound Jun 24 '15 at 16:27
  • Note that in a Windows console, the `Ctrl-Z` will only be recognised as `EOF` when it immediately follows a `newline`, otherwise it is treated as value `26`. – Weather Vane Jun 24 '15 at 16:50

2 Answers2

2

-1 is actually two separate characters - and 1 which is not equivalent to EOF. Use Ctrl + d on Linux or Ctrl + z on Windows.

haccks
  • 104,019
  • 25
  • 176
  • 264
2

As @SouravKanta alludes to: your loop is reading individual characters one at a time, so if you enter -1, it reads the - and then the 1, neither of which indicates EOF. I believe Cntl-d is what you want, at least in *nix (you don't specify the platform).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101