英文:
Why I could not print char variable?
问题
我不知道为什么这段基本代码不起作用:它只打印第一个变量而不是第二个:
b=a
y=b
#include <stdio.h>
int main() {
int b, y;
b = getchar();
putchar(b);
y = getchar();
putchar(y);
return 0;
}
输出是:
/tmp/urA18H7eDx.o
a
a
b
dash: 2: b: not found
英文:
I don't know why this basic code doesn't work well: it's printing just the first variable but not the second:
b=a
y=b
#include <stdio.h>
int main() {
int b, y;
b = getchar();
putchar(b);
y = getchar();
putchar(y);
return 0;
}
The output is:
/tmp/urA18H7eDx.o
a
a
b
dash: 2: b: not found
答案1
得分: 1
以下是执行所发布程序时发生的情况:
b = getchar();从标准输入请求输入。- 输入流缓冲区中没有待处理的输入,因此从终端请求输入。
- 您键入
a,然后按 Enter 键。 - 终端处于行缓冲模式,因此 Enter 键会在输入流中产生一个换行字符,并在将
a和换行回显到终端后返回程序控制(发布的执行跟踪中的第一个a)。 getchar()返回输入流缓冲区中可用的第一个字节,即字符a。putchar(b);将a输出到标准输出。标准输出被行缓冲到终端,因此字符只会存储在输出缓冲区中,直到输出换行符为止。y = getchar();从标准输入读取下一个字节,即由上一个输入键入的换行符。putchar(y);将换行符输出到标准输出。输出行被刷新,产生a和一个换行符(发布的执行跟踪中的第二个a)。- 如果您随后键入
b并按 Enter 键,Shell 将将此行读取为命令并尝试执行b程序,但找不到该程序,从而生成错误消息dash: 2: b: not found。
如果您在shell窗口中测试程序,您可能会看到第二个 a 输出行后的shell提示符。
英文:
Here is what is happening when you execute the posted program:
b = getchar();requests input from standard input.- no input is pending in the input stream buffer so input is requested from the terminal.
- you type
aand hit the <kbd>Enter</kbd> key. - the terminal is line buffered so the <kbd>Enter</kbd> key produces a newline character in the input stream and control is returned to the program after echoing the
aand the newline to the terminal (firstain the posted execution trace). getchar()returns the first byte available from the input stream buffer, namely theacharacter.putchar(b);outputs theato standard output. Standard output is line buffered to the terminal so the character is just stored in the output buffer until a newline is output.y = getchar();reads the next byte from standard input, which is the newline produced by the <kbd>Enter</kbd> key typed for the previous input.putchar(y);outputs the newline to standard output. The output line is flushed, producing theaand a newline (secondain the posted execution trace).- if you then type
band hit the <kbd>Enter</kbd> key, the shell will read this line as a command and try and execute thebprogram, which cannot be found, producing the error messagedash: 2: b: not found
You might be using some sort of IDE terminal window, if you were testing your program in a shell window, you would see the shell prompt after the second a output line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论