Thread: Error Check for scanf using while loops?

  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    3

    Error Check for scanf using while loops?

    I've been trying to do an error check for my program, for scanf using a while loop, but I am unsure of how to do this.
    I want to make sure the user inputs between 4 and 8 for number of judges, and the score doesn't go below 0 or above 10.
    could someone please help me out?
    Thanks!

    Code:
    
    
    #include<stdio.h>
    
    int i,j,k, judges;
    float max, min,total;
    
    int main(){
       max =0.0;
       min =10.0;
       judges =0;
       total =0;
    
    printf("Enter number of judges between 4-8: ");
    scanf("%d",&judges);
    
        float scores[judges];
    
    for(i =0; i < judges; i++){
        printf("Enter a score for judge %d : ", i +1);
        scanf("%5f",&scores[i]);
    }
    for(j =0; j < judges; j++){
        if(min > scores[j]){
            min = scores[j];
        }
        if(max < scores[j]){
            max = scores[j];
        }
    }
    for(k =0; k < judges; k++){
        total = total + scores[k];
    }
    total = total-max-min;
    printf("max = %4.1f    min = %4.1f    total = total = %4.1f", min,   max,total);
    }
    
    

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    You simply keep calling scanf until the user inputs the numbers you want. Here, a do-while loop would be more intuitive, like this:
    Code:
    do {
        // Check in case user gives a letter or something
        if (scanf("%d", &input) != 1) {
            getchar(); // Discard that extra character
        }
    } while (low <= input && input <= high);
    or even better, you can make that code into a function for maximum re-usability.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bug with scanf and loops
    By Kevin Nguyen in forum C Programming
    Replies: 1
    Last Post: 01-28-2014, 09:17 PM
  2. Check if input is an integer using only loops
    By mababaan in forum C Programming
    Replies: 10
    Last Post: 11-03-2013, 08:19 PM
  3. Using loops for check a roman number input.
    By eryell in forum C++ Programming
    Replies: 9
    Last Post: 04-12-2006, 11:04 AM
  4. Check for error in scanf()
    By Dangerous Dave in forum C Programming
    Replies: 5
    Last Post: 12-08-2001, 06:15 PM
  5. A question about loops and scanf
    By mzkhadir in forum C Programming
    Replies: 3
    Last Post: 10-04-2001, 10:35 AM

Tags for this Thread