1

So like what the title suggest i have tried to use putchar() to print a result of a not equal to test != but the output i got is a question mark.

Here is the code:

#include <stdio.h>
main()
{

    int c;
    c = getchar() != EOF;
    putchar(c);
}

I have used printf() and it works:

#include <stdio.h>
main()
{

    printf("%d",getchar()!=EOF);
}

My question is: Why it doesn't work with putchar?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
mrnamya98
  • 13
  • 3
  • Since the code version with printf "works" please explain what it does and what exactly you are trying to achieve by `getchar()!=EOF`. Maybe explain by adding equivalent `()`. – Yunnosch Oct 19 '19 at 10:15
  • https://stackoverflow.com/editing-help – Yunnosch Oct 19 '19 at 10:17
  • I am trying to answer the exercice 1-7 in **The C programming language** book which ask to verify that the expression```getchar()!=EOF``` is 0 or 1 – mrnamya98 Oct 19 '19 at 10:31

2 Answers2

1

First, accepting that the comparison getchar()!=EOF will yield a Boolean value, which will be converted to either 1 (for true) or 0 (false) when interpreted as any integral type, the statement:

printf("%d",getchar()!=EOF);

prints the value of this conversion as a formatted integer - so you will see "1" or "0" printed.

However, the statement:

putchar(c);

outputs the the actual character represented by the value of c (frequently, but not necessarily, the ASCII value). The characters represented by 0 and 1 are not 'printable' characters, so your console will display something indicating that - in your case, a question mark.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

putchar sends a character, identified by its code value, to standard output. 0 and 1 are not, in most C implementations, codes for the characters “0” or “1”. To get a code value for “0” or “1” from an int c containing 0 or 1, use '0' + c.

printf("%d",getchar()!=EOF) formats the argument value as a decimal numeral, so it generates the appropriate characters.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312