在 C 中打印布尔结果
我读到
int c;
while(c = getchar() != EOF)
{
putchar(c);
}
将根据下一个字符是否为 EOF 来打印值 0 或 1。因为 !=
的优先级高于 =
。
但是当我在 GCC 中运行这个程序时,我得到一个看起来像
|0 0| 的 字符
|0 1|
作为我按 Enter 时的输出。
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 character that looks like
|0 0|
|0 1|
as output when I press Enter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
putchar
打印一个字符。通过打印值 0 和 1,您将打印 null 和 标题开始 (SOH) 字符,都是控制字符。您需要将数字 0 和 1 转换为可打印的内容,方法是直接从 0 或 1 计算可打印值:或使用
c
决定要打印的内容。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:or using
c
to decide what to print.除了每个人都说
c
是不可打印字符之外,无论如何,您都不会为EOF
打印出0
,因为您不是在这种情况下将进入 while 循环。循环后您需要一个额外的putchar
。In addition to what everyone said about
c
being a nonprintable character, you would never print out a0
forEOF
anyway, since you're not going to go into the while loop in that case. You would need an extraputchar
after the loop.这就是在您的程序中为
int
保留空间(将该空间称为c
)而发生的情况,而不必担心其内容。
括号中的内容可以写成
c = (getchar( ) != EOF)
因为赋值运算符的优先级低于不等运算符。getchar()
等待按键并返回按下的按键的值1
1
被放入名为c
的空间中。然后,在 while 循环内,
您将打印值为 1 的字符。正如您所注意到的,在您的计算机上,值为 1 的字符在显示时没有漂亮的格式:)
如果您确实想打印值 < code>0 或
1
具有漂亮的格式,请尝试此如果您想将 0 到 9 之间的值打印为字符,请尝试此
This is what happens in your program
reserve space for an
int
(call that spacec
) and don't worry about its contents.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 pressed1
1
gets put in the space with namec
.Then, inside the while loop
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
or1
with beautiful formats, try thisIf you want to print a value between 0 and 9 as a character, try this
您正在使用 Unicode 控制台。所有不可打印的字符(例如值为 0 和 1 的字节)都会转换为 2x2 矩阵,显示其 Unicode 值。 (此外,对于未安装字体的所有可打印字符。)
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.)