Consider the code below:
#include<stdio.h>
int main(){
char c;
while( ( c=getchar() ) != EOF )
printf("%c\n",c);
return 0;
}
I gave the input as: hi^Z
The output was:
h i (an arrow pointing towards left)
[Sorry, I couldn't find character for the above arrow. ]
Can someone please explain the output ? Since ^Z is part of the character string and there are characters to flush, I think ^Z shouldn't have been passed and thus the output should be,
h i (new line )
P.S - I am on windows and ^Z thus is EOF.
Refer http://www.cplusplus.com/reference/cstdio/getchar/ It says that return type of
getchar
isint
. Compiler should have given warning. Please do not ignore such warnings.You are assigning
int
tochar
which will result in loss. Try to get it intoint
and print it.You can print
int
too inprintf
using%c
and typecasting tochar
.The problem here is, a
char
is not sufficient to hold a value ofEOF
. You need to make use of anint
type.Change the
char c;
toint c;
.That said, the
getchar()
will return any pending items in the standard input. If you use the key combo after some input, the action would be similar as flushing the stream. To get theEOF
returned fromgetchar()
, you need to press the key combination one more time.In short, if you expect
getchar()
to returnEOF
on CTRL+Z make sure there's nothing instdin
.That said, for a hosted environment, the proper signature of
main()
isint main(void)
, at least.