Search code examples
cinfinite-loop

Can't get out of an infinite loop


I worked on a simple exercise where i have to ask some mathematical questions and the user need to respond using integer values and I did everything except for the part where when something else than an integer is used i get an infinite loop... I can stop it using a break but i want to be able to ask again the user to input a integer.

Here"s the code, (I use this website to test my code [https://repl.it/languages]) if I could get some insight on it it would be awesome ! Thanks !

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

char ft_op()
{
 srand(time(NULL));
 char lop[4] = "+-/*";
 int rop = rand() % 4;
 char op = lop[rop];

 return op;
 }

 int ft_result(int nb1, int nb2, char op)
  {
   int result = 0;

   if (op == '+')
    result = nb1 + nb2;
   else if (op == '-')
    result = nb1 - nb2;
   else if (op == '/')
    result = nb1 / nb2;
   else
    result = nb1 * nb2;

   return result;
  }

int main(void)
 {
srand(time(NULL));

int nb1;
int nb2;
char op;
int uresult;
int result;
int nbq = 1;
int grade = 0;

while (nbq < 11)
{
  nb1 = rand()%101;
  nb2 = rand()%101;
  op = ft_op();
  result = ft_result(nb1,nb2,op);

  printf("\nQuestion %d : Calculez %d %c %d = ",nbq, nb1, op, nb2);
  if (scanf("%d", &uresult) != 1)
  { 
   printf("\nErreur de saisie. Veuillez recommencer.\n");
   break;
  }
  else
    {
      nbq = nbq + 1;
      if (result == uresult)
      {
        grade = grade + 1;
        printf("\nBravo vous avez deviné juste !\n");
      }
      else
        printf("\nPas de chance, votre résultat est %d et le bon résultat %d\n",uresult, result);
    }
}
printf("\nVotre note finale est de %d/10", grade);
return 0;
}

Solution

  • You need to clear/absorb the input stream when the input is not a number.

    int c   
    while ((c = getchar()) != '\n' && c != EOF);
    

    The loop above will keep taking a char from the input till it finds a new line or the EOF (End of file). It doesn't need to do anything with the input so there is no body block.

    Replace break; with continue;

    if (scanf("%d", &uresult) != 1) { 
       printf("\nErreur de saisie. Veuillez recommencer.\n");
    
       int c   
       while ((c = getchar()) != '\n' && c != EOF);
    
       continue;
    }