Reputation: 69
Could anyone please explain to me why my while loop won't end when i enter character 'Q'? It kept on looping even though i set my boolean value to false when the user enter 'Q', it supposed to end after that scanf for char input
.
My code:
#include <stdio.h>
typedef int bool;
#define true 1
#define false 0
int main(void) {
char input;
char output;
bool tf = true;
printf("Welcome to the Coder!\n");
while (tf) {
printf("Choose Input (H,A,B,Q) : ");
scanf_s(" %c\n", &input);
if (input == 'Q') {
tf = false;
}
else {
printf("Choose Output (H,A,B) : ");
scanf_s(" %c\n", &output);
}
}
return 0;
}
Upvotes: 2
Views: 2538
Reputation: 550
You should add if
(input == 'Q' || input == 'q')
Also why did you add typedef int bool;
? This was unneeded.
I replace scanf_s
to scanf
because my compiler doesn't recognize it(accidentally solving problem.
because it is better. When I compile this there was no errors.
Compiled - > Compiled Code
Upvotes: 1
Reputation: 48736
The problem is the weird case of scanf_s
. Accord to MSDN, you read single characters using this syntax:
scanf_s(" %c", &input, 1);
Remove the \n
from scanf_s
and add the 1 parameter so it knows to read only 1 character.
Upvotes: 4
Reputation: 5291
I am suspecting that you are entering small letter q on your console:
I would suggest you to change your code to:
if (input == 'Q' || input == 'q') {
tf = false;
}
Upvotes: 3