You will only get an EOF
from the stream when the end of file is reached, not the end of line. How you signal an end of file depends on your OS and terminal settings.
It's usually CTRLd on UNIX-type systems and CTRLz on Windows. For UNIX in cooked mode (normal input mode), you'll generally have to enter it as the first character of a line and follow it with a newline (ENTER).
With Windows, the CTRLz can be entered anywhere on the line, but still needs to be followed by a newline.
In UNIX, the actual character to inform the terminal interface that you want to send EOF
can be set with the stty
command. If you execute stty -a
, you'll see something like:
speed 38400 baud; rows 45; columns 150; line = 0;
intr = ^C; quit = ^\; erase = ^H; kill = ^U; eof = ^D;
eol = <undef>; eol2 = <undef>; swtch = ^Z; start = ^Q;
stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V;
flush = ^O; min = 1; time = 0; -parenb -parodd cs8 -hupcl
-cstopb cread -clocal -crtscts -ignbrk brkint -ignpar -parmrk
-inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany
-imaxbel opost -olcuc -ocrnl onlcr -onocr -onlret -ofill
-ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo
-echoe -echok -echonl -noflsh -tostop -echoctl -echoke
You can see at the end of the second line that eof
is set to ^D
(CTRLd). You can change this with:
stty eof ^x
to set it to CTRLx, for example. You can also set a huge number of other things, most of which will make your current terminal unusable, so be careful :-)
Bottom line, if you want to signal your program that the file is finished, use CTRLd for UNIX (or check stty
if that doesn't work) or CTRLz for Windows. If you want to just get a line of input, use the \n
character in your code as follows:
#include <stdio.h>
int main (void) {
long nc = 0;
while(getchar() != '\n')
++nc;
printf("%ld\n", nc);
return 0;
}