I'm new cs student, i've only been studying for less than two months now so please bear with me. This is also my very first question here on Stackoverflow, I would greatly appreciate if someone help me with this problem.
So, I have made a function that receives input from the user.
1| int getInput()
2| {
3| int x;
4| fflush(stdin);
5| printf("Enter amount: ");
6| scanf("%d%*c", &x);
7| validate(x);
8| return x;
9| }
After getting input an input from the user, it calls validate() function to do input validation.
10| void validate(int x)
11| {
12| bool valid = false;
13| do
14| {
15| if ((x >= 5) && (x <= 95) && (x % 5 == 0))
16| {
17| printf("Amount accepted!");
18| valid = true;
19| }
20| else
21| {
22| printf("Invalid input");
23| askQuit();
24| getInput();
25| }
26| } while (valid == false);
27| return;
28| }
If the user entered a valid input, it breaks the loop then go back to main to proceed. But if the input is not valid, it calls another function askQuit() to ask the user if they want to terminate the program.
29| void askQuit()
30| {
31| char quit;
32| do
33| {
34| fflush(stdin);
35| printf("Would you like to quit? y/n: ");
36| scanf("%c%*c", &quit);
37|
38| tolower(quit);
39| switch (quit)
40| {
41| case 'y':
42| exit(0);
43| case 'n':
44| break;
45| default:
46| printf("Invalid input. Try Again.");
47| }
48| } while(quit != 'n');
49| return;
50| }
If the user don't want to continue, program gets terminated. But if they continue, it breaks the loop and returns to proceed in line 24 to call the getInput() function to ask for user input again.
The whole program works perfectly fine when a valid input entered the first time. But if we enter an invalid input, the next time we enter a correct input is where the problem arise. It tends to execute both if and else statements inside the validate() function. Why does this happen? I spent hours trying to analyze why the program behave this way, but I can't seem to think of a reason.
If someone can explain it to me I would be very grateful! Thanks!