Saturday, October 29, 2022

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

Issue

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!


Solution

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

   ...
}


Answered By - ikegami
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.