为什么要使用 getchar 读取和打印整个字符串?

Why is an entire string being read and printed with getchar?

#include <stdio.h>
void main()
{
char c = getchar();
while ( c != '.')
{
putchar(c);
c = getchar();
}
}

当您 运行 上面的代码并输入 "Shubham jain" 之类的任何字符串时。整个字符串被复制并打印出来,而 getchar() 应该只读取字符串中的第一个字符。谁能解释这是怎么回事?

当您使用程序输入字符串时,它会自动为 getchar 函数中字符串中的每个字符提供输入,并多次调用它。循环检测到 '.' 的那一刻程序停止读取更多字符。

因此输入字符串被缓冲,下次调用 getchar() 时,它不会再次等待用户输入新字符,而是从输入缓冲区中取出它。

getchar 不是 char 它实际上是 int。通常,您可以将输入 getchar 的内容存储为一个整数并将其转换为一个字符。现在,为什么它会阅读所有内容? getchar doesn't have a specific size that it reads but that has to do more with theEOF. usegetc` 读取单个字符。