我不明白为什么条件不能反映结果。我输入的值不等于条件中指定的值,并且仍然打印。有人可以向我解释为什么会出现这种情况。为什么即使scanf中的输入值不等于1,printf函数也会输出值输入
#include<stdio.h>
int main() {
int n;
while (scanf("%d", &n) == 1)
printf("%d\n",n);
return 0;
}
我不明白为什么条件不能反映结果。我输入的值不等于条件中指定的值,并且仍然打印。有人可以向我解释为什么会出现这种情况。为什么即使scanf中的输入值不等于1,printf函数也会输出值输入
#include<stdio.h>
int main() {
int n;
while (scanf("%d", &n) == 1)
printf("%d\n",n);
return 0;
}
我想,你是不是有1 所以正确的变量n的比较,如果我没有错。尝试比较n与1.
int main() {
int n;
while (scanf("%d", &n) == 1){
if(n!=1){
break;
}
printf("%d\n",n);
}
return 0;
}
这可能是一个马虎的答案,但它是一个例子。
的问题是,你是不是比较n
的值,它是输入读取,而是由scanf
功能这是你必须投入数返回的值,你的情况是始终为1
更多细节:Value returned by scanf function in c
此代码应在你的情况作品:
#include<stdio.h>
int main() {
int n;
scanf("%d", &n);
while(n == 1){
printf("%d\n",n);
scanf("%d", &n);
}
return 0;
}
您应该仍然检查返回值。如果用户输入无效值,您将读取未初始化的值'n'。 – user694733
还要考虑如果我输入'1 x'会发生什么。 –
scanf
返回的输入数量读取和分配,而不是输入的值本身。在这种特殊情况下,您只需要一个输入,因此scanf
将在成功时返回1,在匹配失败时返回0(即,输入不是以小数位开始),或者如果EOF发现文件结束或者一个错误。
如果你想测试对输入的值,你会做这样的事情
while(scanf(“%d”, &n) == 1 && n == EXPECTED_VALUE)
{
printf(“%d”, n);
}
编辑
其实,一个更好的方式做这将是这样的:
int n;
int itemsRead;
/**
* Read from standard input until we see an end-of-file
* indication.
*/
while((itemsRead = scanf("%d", &n)) != EOF)
{
/**
* If itemsRead is 0, that means we had a matching failure;
* the first non-whitespace character in the input stream was
* not a decimal digit character. scanf() doesn't remove non-
* matching characters from the input stream, so we use getchar()
* to read and discard characters until we see the next whitespace
* character.
*/
if (itemsRead == 0)
{
printf("Bad input - clearing out bad characters...\n");
while (!isspace(getchar()))
// empty loop
;
}
else if (n == EXPECTED_VALUE)
{
printf("%d\n", n);
}
}
if (feof(stdin))
{
printf("Saw EOF on standard input\n");
}
else
{
printf("Error while reading from standard input\n");
}
'scanf'可以返回'EOF',所以除了你的'如果(N!= 1)'检查,你的'while'条件应该是'而(scanf函数( “%d”,&N) == 1)'。 – user694733