为什么我无法打印字符变量?

huangapple go评论62阅读模式
英文:

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 &lt;stdio.h&gt;

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 a and 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 a and the newline to the terminal (first a in the posted execution trace).
  • getchar() returns the first byte available from the input stream buffer, namely the a character.
  • putchar(b); outputs the a to 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 the a and a newline (second a in the posted execution trace).
  • if you then type b and hit the <kbd>Enter</kbd> key, the shell will read this line as a command and try and execute the b program, which cannot be found, producing the error message dash: 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.

huangapple
  • 本文由 发表于 2023年7月23日 17:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定