user13343210
user13343210

Reputation:

How to access return value of scanf when used in a while loop?

The intention of this code is to wait for the user to input two integers and then to do something with them. However I don't want my program to stop when the 2 values are read, instead, I want it to follow the directions that are inside the while loop and when it's done, ask the user for some more integers.

int main (void){
    while(scanf("%d %d", &order, &system) != EOF){
    
        if(order < 0 || system < 2 || system > 36){
            printf("Invalid input!\n");
            return 1;
        }
        // Do something with the numbers 

    }
    return 0;
}

The problem I am facing here is that I can't figure out how to store the return value of scanf, so that I could check if it did indeed obtain two integers. Normally I would just write if( scanf ( ... ) != 2 ) { return 1; }.

Thanks!

Upvotes: 1

Views: 220

Answers (1)

ikegami
ikegami

Reputation: 385546

while (1) {
   int rv = scanf("%d %d", &order, &system);
   if (rv == EOF) {
      ...
   }

   ...
}

Upvotes: 1

Related Questions