Home > database >  Little character counter program using getchar() returns twice as much as the expected result
Little character counter program using getchar() returns twice as much as the expected result

Time:03-21

How come this little program returns twice as much as the expected result ?

int counter=0;
while(getchar()!=EOF)  counter;
printf("%d\n",counter);

The goal of this program is to print the number of input characters it gets from the keyboard until EOF signal is received ( I'm using unix so ctr D). However this is the result on my terminal after I start the program, input inside it a 'c' character from the keyboard and then give it the ctr D signal :

c

2D

As you see the counter is unexpectedly 2. Moreover what that D stands for ?

CodePudding user response:

Well, I'm going to guess that your input was:

:
C
2
^D

which would be ":\nC\n2\n^D". The newlines would account for the extra chars.

If you did actually send ^D that would be the same as 13 (0xD) aka carriage return or \r. When you print the carriage return the cursor goes to the beginning of the line and then you print your character count over whatever char was there.

CodePudding user response:

Terminals usually get input lines from the user, and pass them on to programs. A line of text is terminated by the end-of-line byte, \n. So you, as a user, have to press Enter and send this end-of-line byte to your program, if you want your program to get any input at all. Your program then counts this byte as a normal byte.

Try supplying 9 bytes of input to your program by typing something. Your program will wait for your input, and then get 10 bytes in a quick succession: s, o, m, e, t, h, i, n, g, \n.


One way to send just 1 byte to your program is to redirect its standard input:

program <input.txt

where the file input.txt contains just one byte.

  • Related