The getchar()
function reads a single byte from stdin
, and returns the value of that byte. For example, on an ASCII based system, the byte value 32 represents a space, the value 33 represents an exclamation point (!
), the value 34 represents a double quote ("
), and so on. In particular, the characters -
and 1
(which make up the string "-1"
) have the byte values 45 and 48 respectively.
The number -1 does not correspond to any actual character, but rather to the special value EOF
(an acronym for end of file) that getchar()
will return when there are no more bytes to be read from stdin
. (Actually, the EOF
value is not guaranteed by the C standard to be equal to -1, although on most systems it is. It is guaranteed to be less than zero, though.)
So your loop, as written, will continue to run until there's no more input to be read. If you're running your code from a terminal, that basically means it will keep running until you type Ctrl+D (on Unixish systems) or Ctrl+Z (on Windows). Alternatively, you could run your program with its input coming from a file (e.g. with my_program < some_file.txt
), which would cause the loop to run until it has read the entire file byte by byte.
If you instead want to read a number from stdin
, and loop until the number equals -1, you should use scanf()
instead.