david becker
david becker

Reputation: 45

getchar is printing extra output

root@ubuntu:~/DH$ cat E1-6.c 
#include<stdio.h>
main()
{
    int c;
    while(c = (getchar() != EOF)) {
        printf("HI: %d",c);
        //putchar(c);
    }
}
root@ubuntu:~/DH$ cc E1-6.c
root@ubuntu:~/DH$ ./a.out 
1
HI: 1HI: 1

I gave input as 1 using key board but in output it is displayed twice. Can someone please explain what's happening here?

Upvotes: 3

Views: 568

Answers (3)

cxw
cxw

Reputation: 17041

The error happens because, as the comments noted, the "1" is a key and the "enter" press after the 1 (or Ctrl-D for EOF) is another key. As for why both are printing out "1", it is because you are setting c to be the boolean (true/false) value of getchar() != EOF. What I think you want is

while ((c = getchar()) != EOF)

at the top if your loop. That will save the pressed key into c and then check for EOF.

Upvotes: 6

Dan
Dan

Reputation: 10786

Your while statement isn't working correctly. Try running your program with the input "2", I think you will have an interesting result.

Your input is the character 1, followed by a newline \n, and then EOF. The first call to getchar returns 1, 1 is not EOF, so c = 1. The second call returns \n, \n is not EOF, so again c = ('\n' != EOF) which means c = 1.

Try instead:

while((c = getchar()) != EOF) {

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 59997

I think

while(c = (getchar() != EOF)) {

should be

while((c = getchar()) != EOF) {

as c should be assigned not to the comparison but to the return value from getchar

Upvotes: 0

Related Questions