#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main(int argc, char * argv[])
{
printf("This program tests your integer arithmetic skills.\n"
"You should answer the questions following the same \n"
"rules that computers do for integers arithmetic, not \n"
"floating-point arithmetic. Hit the 'Enter' key after \n"
"you have typed in your input. When you wish to finish \n"
"the test, enter -9876 as the answer to a question.\n"
"\n");
int n1, n2, answer, user_answer, a, b, int_per;
char op, c;
float per, count, count_r, count_w;
count = 0;
count_r = 0;
count_w = 0;
printf("What is your question? ");
scanf("%d %c %d", &n1, &op, &n2);
do
{
count++;
printf("What is %d %c %d ? ", n1, op, n2);
if (op == '+')
{
answer = n1 + n2;
}
else if (op == '-')
{
answer = n1 - n2;
}
else if (op == '%')
{
answer = n1 % n2;
}
else if (op == '/')
{
answer = n1 / n2;
}
else if (op == '*')
{
answer = n1 * n2;
}
c = scanf("%d", &user_answer);
if (user_answer == answer)
{
printf("Correct!\n\n");
count_r++;
}
else if (user_answer == -9876)
{
count = count - 1;
break;
}
else if (c != 1)
{
printf("Invalid input, it must be just a number\n\n");
printf("What is %d %c %d ? ", n1, op, n2);
}
else if (user_answer != answer)
{
printf("Wrong!\n\n");
count_w++;
}
} while(user_answer != -9876);
per = (count_r / count) * 100;
a = (int) count_r;
b = (int) count_w;
int_per = roundf(per);
printf("\nYou got %d right and %d wrong, for a score of %d%c\n", a,
b, int_per, 37);
return EXIT_SUCCESS;
}
The code above is supposed to loop through asking for questions and then the answer, until the user inputs -9876 as an answer then the program terminates and gives them their score.This all works EXCEPT!! for one thing. When the user enters a non number into the input. When this happens it is supposed to say "invalid input, please try again" then ask the same question again. For example
What is your question? 9+9
What is 9 + 9? hmmm, 8
invalid input, please try again
What is 9 + 9?
SO.. the user entered "hmmm" and instead of prompting the user with the same question again then scanning properly it just jumps into an infinite loop.I was wondering how to fix that.
Thanks