C Scanf突然停止读取数值
我正试图在我的Mac上运行一个简单的C程序。 它工作正常一段时间但突然scanf停止工作。 我基本上想要读取整数值并输出输入的内容。 无论我输入的整数,程序都保持输出0.我已经尝试了这里的建议,但没有任何作用。 我已尝试在终端和xcode中运行程序,但仍然没有。 有任何想法吗?
#include 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; }
当您在scanf/fscanf/sscanf
格式字符串中包含任何非格式字符时,这意味着您需要在输入流中使用这些字符(或者在sscanf
情况下输入字符串)。 如果输入中不存在这些字符,则scanf
失败。 空格字符具有特殊含义,导致scanf
跳过所有空格,但不需要任何空格。
所以,为了使这个scanf
成功
scanf("Number of elements: %d", &numberOfElements);
你必须从字面上进入
Number of elements: 10
要么
Numberof elements:10
要么
Numberofelements: 10
或类似的东西。 即你必须输入单词Number
, of
, elements
和:
。 如果您只输入10
,则scanf
将失败,因为仅仅10
与请求的格式不匹配。
我确定这不是你的意图。 显然,你真正想做的是使用printf
打印提示,然后做一个简单的操作
scanf("%d", &numberOfElements);
scanf
的上述特征可能很有用,但可能只在少数情况下使用。 这意味着当您在scanf
格式字符串中看到任何非格式文本时,很可能出现问题。
您必须打印提示,并且只扫描输入:
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); /* ... */ } }
您不应该在scanf
语句中Number of elements:
。 您想将scanf
语句更改为:
printf ( "Number of elements: " ); scanf ("%d", &numberOfElements );