问题描述
我有以下程序:
#include <stdio.h> int main() { int ch; while( ch = getchar() != '\n') { printf("Read %c\n",ch); } return 0; }
无论我输入什么,我都会得到:
No matter what I enter I get:
Read
为什么会这样?我看到的是什么奇怪的字符?
Why is this happening and what is that weird char that I see?
Stackoverflow没有打印出奇怪的字符.您可以在这里看到它: http://ideone.com/EfZHr
Stackoverflow is not printing the weird char. You can see it here: http://ideone.com/EfZHr
推荐答案
您需要将括号放置为:
while( (ch = getchar()) != '\n')
的
优先级 大于=
while( ch = getchar() != '\n')
与:
while( ch = (getchar() != '\n') )
读取char的
将其与换行符进行比较,然后将比较结果分配给ch.现在比较的结果是0(输入换行符时)或1(输入其他任何内容时)
which reads a char compares it with newline and then assigns the result of comparison to ch. Now the result of comparison is 0 (when newline is entered) or 1 (when anything else is entered)
您看到的奇怪字符是 控制字符 的值为1,没有ASCII 1的可打印符号,因此我猜想它是在其中打印出值为0001的奇怪字符的shell.
The weird char you're seeing is the control char with value 1, there is no printable symbol for ASCII 1, so I guess its the shell that prints the weird char with value 0001 in it.
您可以通过将程序输出管道传输到八进制转储(od)来确认:
You can confirm it by piping your program output to octal dump (od) :
$ echo 'a' | ./a.out | od -bc # user entered 'a' 0000000 122 145 141 144 040 001 012 R e a d 001 \n here you go ----------------^ $ echo '\n' | ./a.out | od -bc # user entered '\n' 0000000
与-Wall一起使用时的GCC警告您:
GCC when used with -Wall warns you as:
warning: suggest parentheses around assignment used as truth value
这篇关于为什么此C程序在输出中输出奇怪的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!