我编写了一个程序来逐个字符地读取输入并将其打印到输出,这是我的代码:
#include <stdio.h>
main()
{
int c;
while((c = getchar()) != EOF)
{
printf("%s\n", "log1");
printf("%c\n", c);
printf("%s\n", "log2");
}
}
这是结果:
a(my input)
log1
a
log2
log1
log2
但它应该有这样的结果:
a
log1
a
log2
这个程序有什么问题?
最佳答案
您输入 a 和换行符
a(my input) You are giving a and newline
//this is because of a
log1
a
log2
//this is because of newline
log1
log2
检查换行符并避免打印换行符。
while((c = getchar()) != EOF)
{
if(c!='\n')
{
printf("%s\n", "log1");
printf("%c\n", c);
printf("%s\n", "log2");
}
}
关于c - 为什么 while 中的 getchar 在第一次迭代后不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342434/