below is the code
Code :
#include <stdio.h>
int main(void)
{
int ch开发者_运维知识库;
while((ch = getchar()) != 'h')
putchar(ch);
return 0;
}
Question :
1.)So as usual i just run this code , due to curiosity when the program prompt for input , i insert ^z(CTRL + Z)
which is EOF (Windows 7 Command Prompt)
, but all i get is infinite looping of character printing.
2.)From the code , my logic is that since i input ^z
to the program , it'll just evaluate the logic (ch = getchar()) != 'h'
and value true
or 1
will be returned and character ^z
will be printed out.But instead different result is yield.
When you press ^Z
, the program notices the input stream was closed, but you keep on using getchar()
, so you get EOF
. This loops infinitely, since you can't input 'h'
anymore. Note that only 'h'
(not 'A'
, not ^M
, and also not ^Z
) can stop the program, since you loop if you don't get a 'h'.
In other words, if you want to stop if anything else but 'h'
is entered, then do
do
{
ch = getchar();
putchar(ch);
} while (ch == 'h');
EOF is typically defined as -1 (but it's implementation specific). When you call putchar(-1), it will be converted to unsigned char, and become the value 255, which is then output (ÿ unless I'm mistaken).
EOF is an integer with an implementation-defined negative value. Your code loops indefinitely because only entering 'h' would make it finish. But once it reads EOF, which is != 'h'
, it enters an infinite loop because the standard input is closed and there is nothing that can make it return anything else.
精彩评论