C Scanf突然停止读取数值 [英] C Scanf suddenly stopped reading in values
问题描述
我正在尝试在Mac上运行一个简单的C程序。它工作正常一段时间但突然scanf停止工作。我基本上想要读取整数值并输出输入的内容。无论我输入的整数,程序都会保持输出0.我已经尝试过建议这里但没有任何作用。我已尝试在终端和xcode中运行程序,但仍然没有。有什么想法吗?
I'm trying to run a simple C program on my Mac. It worked fine for a while but then suddenly scanf stopped working. I basically want to read in an integer value and output what was entered. No matter the integer I enter the program keeps outputting 0. I've tried the suggestions here but nothing works. I've tried running the program in both terminal and xcode but still nothing. Any ideas?
#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;
}
推荐答案
当你包含任何非将字符格式化为 scanf / fscanf / sscanf
格式字符串,这意味着要求这些字符出现在输入流(或输入字符串中,如果是 sscanf
)。如果输入中不存在这些字符, scanf
将失败。空格字符具有特殊含义,导致 scanf
跳过所有空格,但不需要任何空格。
When you include any non-format characters into scanf/fscanf/sscanf
format string, it means that you require these characters to be present in the input stream (or input string, in case of sscanf
). If these characters are not present in the input, scanf
fails. Space character has special meaning though, causing scanf
to skip all whitespace, but not requiring any whitespace to be present.
因此,为了使 scanf
成功
scanf("Number of elements: %d", &numberOfElements);
你必须输入,字面上
Number of elements: 10
或
Numberof elements:10
或
Numberofelements: 10
或类似的东西。即你必须输入数字
,的
,元素
以及:
。如果您只输入 10
, scanf
将失败,因为仅仅 10
与请求的格式不匹配。
or something like that. I.e. you have to type in the words Number
, of
, elements
and the :
as well. If you just enter 10
, the scanf
will fail, since a mere 10
does not match the requested format.
我确定这不是你的意图。显然,你真正想做的是使用 printf
打印提示,然后做一个简单的
I'm sure this was not your intent. What you really wanted to do, apparently, is to print the prompt using printf
and then do a simple
scanf("%d", &numberOfElements);
scanf
的上述功能可能很有用,但可能仅在少数情况下。这意味着当您在 scanf
格式字符串中看到任何非格式文本时,很可能出现问题。
The aforementioned feature of scanf
could be useful, but probably only in some rare cases. This means that when you see any non-format text in scanf
format string, there's a good possibility that something is wrong.
这篇关于C Scanf突然停止读取数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!