【发布时间】:2021-11-29 00:10:15
【问题描述】:
我安装了 MingW C 编译器,并尝试在那里编译和运行 C 程序。
我使用 Visual Stdio Code IDE。
操作系统为 WINDOWS 10。
编译器是 MinGW。
我不使用scanf() 或gets() 的程序都运行成功,但是当我使用scanf() 函数时,程序不接受输入。我也使用了gets() 函数,但也有同样的问题。所以当我按下“运行”按钮时,它不会给出任何输出。
这是我最小的可重现示例。这是编译器问题还是我的代码错误?
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
//scanf("%d", &n);
}
以上代码的输出是:
[Running] cd "d:\code\C\" && gcc #13sum.c -o #13sum && "d:\code\C\"#13sum
Enter a number:
[Done] exited with code=0 in 0.29 seconds
如果我添加scanf():
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
scanf("%d", &n);
}
以上代码的输出是:
[Running] cd "d:\code\C\" && gcc #13sum.c -o #13sum && "d:\code\C\"#13sum
[Done] exited with code=1 in 31.526 seconds
使用fflush(stdout);后
#include <stdio.h>
int main()
{
int n;
printf("Enter a number: ");
fflush(stdout);
scanf("%d", &n);
}
[Running] cd "d:\code\C\" && gcc #13sum.c -o #13sum && "d:\code\C\"#13sum
Enter a number:
[Done] exited with code=1 in 2.804 seconds
使用fflush(stdout); printf() 语句后执行但现在我无法输入值。我正在输入,但它没有显示在输出中。
在上述任何情况下,编译器都不会出现任何错误。
【问题讨论】:
-
您在编译时看到了哪些错误?跑吗?
-
“不工作”不是一个有用的问题描述。具体的错误或不正确的行为是什么?
-
“你一直用那个词。我不认为它是你认为的意思。”
-
你需要检查
scanf返回的值,这样你才能检测到输入的结束,如果输入不能用int表示,%d会导致未定义的行为,否则你的代码看起来不错。这个对我有用。输入1 2 3 0得到什么输出?正如预期的那样,我得到 4 个提示和“Sum is = 6”。 -
如果您在打印提示后刷新输出,也许您的困惑会减少。实际上,当您以交互方式运行它时,由于缓冲,您可能看不到提示。 (即
printf("Enter a number: "); fflush(stdout);