If else

Status
Not open for further replies.

lifesamd

Honorable
Jan 14, 2013
41
0
10,530
Hey, I was trying to make a small game like that who wants to be a millionaire thing. The code I wrote was:-
Code:
 printf("Question 1. The question\n\n");
 printf(" a. option a\t b. option b\n c. option c\t\td. option d\n\n");
 
 a = getchar();

 if (a == 'a' || a == 'c' || a == 'd') {
    printf("Sorry that's the wrong answer. Your game ends here");
    printf("But just because this is a trial program.. Keep on playing..\n\n\n");}
 else if (a == 'b')
    printf("Congratulations.. That's the correct answer\n\n");
 else printf("Wrong input\n");

 printf("Question 2. The question\n\n");
 printf(" a. option a\t b. option b\n c. option c\t\td. option d\n\n");
 
 a = getchar();

 if (a == 'a' || a == 'c' || a == 'd') {
    printf("Sorry that's the wrong answer. Your game ends here");
    printf("But just because this is a trial program.. Keep on playing..\n\n\n");}
 else if (a == 'b')
    printf("Congratulations.. That's the correct answer\n\n");
 else printf("Wrong input\n");

But the problem is that, after the first question, when I hit the correct answer and press return, it says "correct answer..." then prints the next question too.. but then instead of getting another character input, it automatically prints "wrong input".. I dont understand this.. Why does the program skip line no. 16? It doesnt even wait for me to enter a character which it would assign to a next. Does it count the return press as a character? If yes, then how to solve this problem?? cant tried scanf instead.. same issue.. I am new to programming. trying to learn.. and cant find any way around this problem..
 

When you read the documentation it is clear that a carriage return (Enter) is a character, so do not press it!
 

lifesamd

Honorable
Jan 14, 2013
41
0
10,530


But then how am i supposed to enter the character?? DOS promt does need me to press an enter after giving the value.. I dont understand..How should I then enter the value? If i only press the character, the prompt will keep on blinking next to the character. only when i press enter, it would run.. :(
 

calmstateofmind

Distinguished


Because you're not flushing the input buffer after each use of getchar(). Add "getchar();" to line 15 and it'll take care of the problem.
 
Status
Not open for further replies.