我正在尝试在我的 Mac 上运行一个简单的 C 程序。它工作了一段时间但突然 scanf 停止工作。我基本上想读入一个整数值并输出输入的内容。无论我输入的整数是多少,程序一直输出 0。我已经尝试了建议 here但没有任何效果。我试过在终端和 xcode 中运行该程序,但仍然没有。有什么想法吗?
#include <stdio.h>
int main(){
int numberOfElements = 0;
scanf("Number of elements: %d",&numberOfElements);
printf("%d\n",numberOfElements); //keeps returning 0 no matter the number I enter
return 0;
}
最佳答案
你必须打印提示,并且只扫描输入:
printf("Number of elements: ");
fflush(stdout);
scanf("%d", &numberOfElements);
一般来说,最好避免直接使用scanf()
。相反,您可以获得一行输入,然后对检索到的字符串使用 sscanf()
以更好地控制错误。
char line[MAX_LINE];
if (fgets(line, sizeof(line), stdin) != NULL) {
if (sscanf(line, "%d", &numberOfElements) != 1) {
printf("You didn't input a number: %s", line);
/* ... */
}
}
关于C Scanf 突然停止读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994747/