繁体   English   中英

为什么即使scanf中的输入值不等于1,printf函数也会打印输入的值

[英]Why does the printf function print the value input even when the input value in scanf is not equal to 1

我不明白为什么其中的条件不能反映结果。 我输入的值不等于条件指定的1,并且仍会打印出来。 有人可以向我解释为什么会这样。

#include<stdio.h>

int main() {
int n; 
while ( scanf( "%d", &n) == 1 )
   printf("%d\n",n);
return 0;
}

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" );
}

我认为您没有正确地将n变量与1进行比较。因此,如果我没有记错的话。 尝试比较n与1。

int main() {
int n; 
while ( scanf( "%d", &n) == 1){
    if(n!=1){
    break;
    }
    printf("%d\n",n);
}    
return 0;
}

这可能是一个草率的答案,但这只是一个例子。

问题是您没有比较n的值(即读取的输入),而是scanf函数返回的值(即您拥有的输入数),在您的情况下始终为1。

更多详细信息: c中的scanf函数返回的值

此代码适用于您的情况:

#include<stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    while(n == 1){
        printf("%d\n",n);
        scanf("%d", &n);
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM