1

I am trying to test whether a number received from scanf is between an acceptable range but the else is triggering when it shouldn't be, if I enter 50, it will print "the number entered is not valid"

 for (int i = 1; i <= 20; ++i) {
    
    bool flag = true; 
    
    while (flag == true) {
        int x  = scanf("%d", &uniqueNumber);
        
        if ( (x > 9) && (x < 101) ) {
            uniqueArray[i] = x;
            flag =false;
        } else {
            printf("The number entered is not  valid");
        }
    }
}
doug22
  • 77
  • 1
  • 8
  • 4
    Please read the [scanf manual](https://www.man7.org/linux/man-pages/man3/scanf.3.html) to understand what the return value actually represents. You should be checking the return value for success or failure. Upon success the input value is read into `uniqueNumber` and thus that is the variable you should be validating for range. – kaylum Jun 17 '22 at 05:41
  • 2
    `scanf` returns the number of fields parsed (in your case it would be 1 unless parsing failed), **not** the value of the field. – wohlstad Jun 17 '22 at 05:42

1 Answers1

-1

I suppose this code would work for you:

for (int i = 1; i <= 20; ++i) {
    bool flag = true;

    while (flag) {
        scanf("%d", &uniqueNumber);

        if (uniqueNumber > 9 && uniqueNumber < 101) {
            uniqueArray[i] = uniqueNumber;
            flag = false;
        } else {
            printf("The number entered is not valid\n");
        }
    }
}
Sunfline
  • 139
  • 2
  • 8