0

I am trying to check that the the user input is a number but I am getting stuck in an infinite loop

here is the code

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

int main(){
    int  counter = 0;
        float marks[8];
    float average = 0.0;
        float sum = 0.0;
   
        printf("Please enter 8 marks and I will calcuate the average and highest mark\n");
        while (counter != 8) {
            printf("%i) ",counter+1);
       if  (scanf("%f", &marks[counter]) == 1){
           sum += marks[counter];
           counter++;
           
       }
        else
        {
            printf("invalid number. try again\n");
          
        }

}

the loop is repeating the else statement when I enter a letter.

the expected outcome when an float value is entered should be "invalid number try again" and then the user can input another number until the array is full.

for example:

1
2
a
invalid number please try again
1
2
1
1
1
1
william_
  • 1,131
  • 6
  • 20
  • What is the desired behavior? – YiFei May 24 '21 at 05:40
  • 2
    `scanf` does not consume the input if it is unable to match it. So it will just keep failing if you keep calling `scanf`. Need to consume the input even when it is incorrect. A common way is to call `fgets` first to ensure input is always read then `sscanf` to parse the string. – kaylum May 24 '21 at 05:42

0 Answers0