0

I do not understand why the condition in does not reflect the results. I input values that were not equal to 1 as specified by the condition and it still printed. Can someone please explain to me why this is the case.

#include<stdio.h>

int main() {
int n; 
while ( scanf( "%d", &n) == 1 )
   printf("%d\n",n);
return 0;
}
AndyG
  • 39,700
  • 8
  • 109
  • 143
Катя
  • 21
  • 1
  • 1
  • 7

3 Answers3

1

scanf returns the number of inputs read and assigned, not the value of the input itself. In this particular case you are only expecting a single input, so scanf will return 1 on success, 0 on a matching failure (i.e., the input doesn’t start with a decimal digit), or EOF if it sees end-of-file or an error.

If you want to test against the value of the input, you’d do something like

while( scanf( “%d”, &n ) == 1 && n == EXPECTED_VALUE )
{
  printf( “%d”, n );
}

Edit

Actually, a better way to do that would be something like this:

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" );
}
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

I think that you are not comparing correctly n variable with 1. So if I dont be wrong. Try to compare n with 1.

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

This can be a sloppy answer, but it is an example.

Hadri
  • 1
  • 6
  • `scanf` can return `EOF`, so in addition to your `if(n!=1)` check, your `while` condition should be `while ( scanf( "%d", &n) == 1)`. – user694733 Oct 06 '17 at 12:27
0

The problem is that you are not comparing the value of n which is the input read, but the value returned by the scanf function which is the number of inputs you have, in your case is always 1.

More details: Value returned by scanf function in c

This code should works in your case:

#include<stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    while(n == 1){
        printf("%d\n",n);
        scanf("%d", &n);
    }
    return 0;
}
EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40