gpt4 book ai didi

c - 在 C 中打印 boolean 结果

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:09 24 4
gpt4 key购买 nike

我读过


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

将根据下一个字符是否为 EOF 打印值 0 或 1。因为 != 的优先级高于 =。

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

当我按下 enter 时作为输出。

最佳答案

putchar 打印一个字符。通过打印值 0 和 1,您正在打印 nullstart of heading (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');
}

或使用 c 来决定打印什么。

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

关于c - 在 C 中打印 boolean 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5168168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com