Home > Software engineering >  Prompting user for input until newline and checks if input is valid
Prompting user for input until newline and checks if input is valid

Time:11-26

This program prompts the user for quiz grades and store them in an array. The user can enter a maximum of 10 grades, but can enter less. The program should error-check: if the user enters an invalid grade, the program should loop until the user correctly enters a valid grade

    #include <stdio.h>
    #define N 10 /* number of students in class */
    int main()
    {
        int quiz[N], /* array of quiz grades */
        grade, /* used to read in one grade */
        last, /* index of last element used */
        i, /* loop variable */
        ib /* input buffer */;
        char c;
        
        last = -1;
     
        printf("Enter the quiz grade: ");
       
        while (ib=scanf("%d",&grade) && last<N-1)
        {
             
            if(ib == 0 ){
                printf("Please enter a valid quiz grade: ");
                while((c=getchar())!='\n' && c!=EOF);
            }
            else 
                if(grade >= 0 && grade <= 10)
                {
                    last  ;
                    quiz[last] = grade;
                }
                else{
                    printf("Enter a quiz grade between 0 and 10");
                }
        }
    }

This code does not stop at the number of grades entered but rather fills the array with the last grade until its size is N.

Also when the user enter a non digit input the program stops when it should prompt the user to enter a valid grade

CodePudding user response:

At least one bug is here:

while (ib=scanf("%d",&grade) && last<N-1)

Assume that scanf returns zero (i.e. ib becomes zero) then the above is the same as:

while (0 && last<N-1)

which is the same as

while (0)

which means that your loop stops when something not being a number is entered.

Also notice that due to the above, ib can not be zero when you execute:

        if(ib == 0 ){
            // So this code can't be reached
            printf("Please enter a valid quiz grade: ");
            while((c=getchar())!='\n' && c!=EOF);
        }

To solve this you can move the scanf out of the while condition. Like:

    while (last<N-1)
    {
        ib=scanf("%d",&grade);
        if(ib != 1 )            // Notice this change
        {
            if (ib == EOF) exit(1);  // Check for fatal input error

            printf("Please enter a valid quiz grade: ");
            while((c=getchar())!='\n' && c!=EOF);

            if (c == EOF) exit(1);  //  Check for fatal input error
        }
        else 
        {
            ...
        }
     }

Also change char c; to int c; as getchar returns an int in order to handle EOF

  • Related