-2

my programe gets 5 grades and calculates average and max values.but when i enter a letter first instead of a grade, it continuously prints "invalid". when i enter a letter after entering a int value it stops further getting remaining values.can someone explain where i am wrong? thank you

#include <stdio.h>
#include <stdlib.h>


int main()
{
    int grade[5];
    int temp;
    int temp2 = 0;
    for(int i = 0; i <= 4; i++) //getting inputs
    {
        printf("enter grade= ");
        scanf("%i", &temp);
        if(temp <= 100 && temp >= 0)
            grade[i] = temp;
        else
        {
            printf("invalid\n");
            i--;
        }
    }

    //print array
    for(int i = 0; i <= 4; i++)
        printf("%i\n", grade[i]);

    //Average
    for(int i = 0; i <= 4; i++)
    {
        temp2 = temp2 + grade[i];
    }

    printf("avg is= %i\n", temp2 / 5);

    //Max
    int mx = grade[0];

    for(int i = 1; i <= 4; i++)
        if(mx < grade[i])
        {
            mx = grade[i];
        }
    printf("max is= %i", mx);

    return 0;
}
Tadeusz A. Kadłubowski
  • 8,047
  • 1
  • 30
  • 37
xandar6
  • 23
  • 3

2 Answers2

0

you can use the following macro instead of using scanf() directelly

#define SCAN_ONEENTRY_WITHCHECK(FORM,X,COND) \
do {\
    char tmp;\
    while(((scanf(" "FORM"%c",X,&tmp)!=2 || !isspace(tmp)) && !scanf("%*[^\n]"))\
            || !(COND)) {\
        printf("Invalid input, please enter again: ");\
    }\
} while(0)

and in your code you call the macro in this way

for(int i = 0; i <= 4; i++) //getting inputs
{
    printf("enter grade= ");
    SCAN_ONEENTRY_WITHCHECK("%i",&tmp,(temp <= 100 && temp >= 0));
    grade[i] = temp;
}

for more details concerning the macro and concerning the reason of getting infinite loop in your code, please refer to Common macro to read input data and check its validity

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

From the scanf man page:

These functions return the number of input items successfully
matched and assigned, which can be fewer than provided for, or
even zero in the event of an early matching failure.

So when the scan fails, you have to read and throw the offending characters, or it will still be in the buffer.

fredrik
  • 6,483
  • 3
  • 35
  • 45