PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

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

 October 29, 2022     c, eof, scanf     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing