2

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; } 
3
  • 2
    Did you press enter after typing Q? Commented Jan 12, 2015 at 3:45
  • 3
    yet another scanf issue? Commented Jan 12, 2015 at 3:45
  • yes i did press enter Commented Jan 12, 2015 at 3:51

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this solved the problem thanks. I don't really need the \n after %c
3

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; } 

1 Comment

Or for that matter, #include <ctype.h> and if(toupper(input) == 'Q').
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.