arya
arya

Reputation: 81

printf printing 2 times output in C

I have just started learning C through book K&R. This is my code.

#include <stdio.h>
int main (){
    int c;
    char value = ((c = getchar()) != EOF);
    while (value){
        printf(" %c\n", c);
        printf("%d :: value : %d\n",__LINE__,value);
        value = ((c = getchar()) != EOF);
    }
    return 0;
}

This results in

a
 a
10 :: value : 1


10 :: value : 1
b
 b
10 :: value : 1


10 :: value : 1

I don't understand why it is printing value 2 times?

Upvotes: 2

Views: 2592

Answers (5)

dragosht
dragosht

Reputation: 3275

Do this simple change in your program:

#include <stdio.h>
int main ()
{
    int c;
    char value = ((c = getchar()) != EOF);
    while (value)
    {
        printf(" %d\n", c); //print the int value of the character
        printf("%d :: value : %d\n",__LINE__,value);
        value = ((c = getchar()) != EOF);
    }
    return 0;
}

And now the output becomes:

a
 97 <-- ascii code of 'a'
9 :: value : 1
 10 <-- ascii code of newline (line feed)
9 :: value : 1
b
 98 <-- ascii code of 'b'
9 :: value : 1
 10
9 :: value : 1
abcd <-- you could also do this
 97
9 :: value : 1
 98
9 :: value : 1
 99
9 :: value : 1
 100
9 :: value : 1
 10
9 :: value : 1
<...>

Showing that every time you read a character a newline (ASCII 10 character) also comes along.

Upvotes: 1

Chunde  Huang
Chunde Huang

Reputation: 385

Not twice it's only once. Another one is your input. For example, you input 'a', the console will display 'a' first, then you program will print one more time when run to the statement:

printf(" %c\n", c);

Upvotes: 3

Daniel Waechter
Daniel Waechter

Reputation: 2763

getchar() is reading two characters - the letter you typed, and the newline character when you pressed "enter".

Upvotes: 2

Max DeLiso
Max DeLiso

Reputation: 1244

This will continue to execute those two printf()s until you encounter EOF on stdin, which will probably signaled by EOT (control D, or control Z on some platforms).

The reason for this is because of the pre-test condition while(value), wherein value is computed as:

((c = getchar()) != EOF);

This means do a blocking read from stdin for one character, storing it in the stack allocated integer c, and then store the result of the comparison with EOF into the char value. Which means that the char value should really probably be a bool, and not a char, as its value will only ever be zero or one.

Upvotes: 2

perror
perror

Reputation: 7386

It is simply because you first see the character you just typed at the terminal and, then, the character that is printed by the program (second one a little bit shifted on the right).

But, if you where speaking about value, it appears only once. The left most value is the content of the variable __LINE__ and the other one is value (see printf format strings to know more about it).

Upvotes: 0

Related Questions