开发者

printing boolean result in C

I read that


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

will print the value 0 or 1 depending on whether the next character is an EOF or not. Because != has a higher precedence than = .

But when I run this program in gcc I get a charact开发者_C百科er that looks like

|0 0|

|0 1|

as output when I press enter.


putchar prints a character. By printing the values 0 and 1, you're printing the null and start of heading (SOH) characters, both control characters. You'll need to convert the numbers 0 and 1 to something that's printable, either by calculating a printable value directly from the 0 or 1:

while (...) {
    // note: the C standard (§ 5.2.1-3 of C99) ensures '0'+1 is '1', which is printable
    putchar(c+'0');
}

or using c to decide what to print.

while (...) {
    if (c) {
        ...
    } else {
        ...
    }
    // or:
    //putchar(c ? ... : ...);
    // though feelings on the ternary operator vary.
}


You are using a unicode-console. All non-printable characters (like the bytes with value 0 and 1) are converted to the 2x2-matrix displaying its unicode-value. (Also, for all printable characters for which you have no font installed)


In addition to what everyone said about c being a nonprintable character, you would never print out a 0 for EOF anyway, since you're not going to go into the while loop in that case. You would need an extra putchar after the loop.


This is what happens in your program

int c;

reserve space for an int (call that space c) and don't worry about its contents.

while(c = getchar( ) != EOF)

The thing in parenthesis can be written as c = (getchar( ) != EOF) because the assignment operator has lower precedence than the inequality operator.

  • getchar() waits for a keypress and returns the value of the key pressed
  • That value is checked against EOF
  • As it's different, the result of the inequality operator is 1
  • and the value 1 gets put in the space with name c.

Then, inside the while loop

{
   putchar(c);
}

you're printing the character with value 1. As you've noticed, on your computer, the character with value 1 does not have a beautiful format when displayed :)


If you really want to print the values 0 or 1 with beautiful formats, try this

c = 0; /* or 1 */
putchar('0' + c);

If you want to print a value between 0 and 9 as a character, try this

c = 5; /* or 7, or 0, ... */
putchar('0' + c);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜