在C中打印布尔结果

Joh*_*ohn 0 c boolean operator-precedence

我看了


int c;
while(c = getchar( ) != EOF)
{
   putchar(c);
}
Run Code Online (Sandbox Code Playgroud)

将打印值0或1,具体取决于下一个字符是否为EOF.因为!=的优先级高于=.

但是当我在gcc中运行这个程序时,我得到一个看起来像
| 0 0 | 的字符
| 0 1 |

当我按回车键输出.

out*_*tis 6

putchar打印一个角色.通过打印值0和1,您将打印空值开始标题(SOH)字符,这两个控制字符.您需要通过直接从0或1计算可打印值,将数字0和1转换为可打印的内容:

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

c用来决定打印什么.

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