Hi, im learning C and am currently learning about single character variables and such.
Now i know a little about IF statements but for some reason the last conditional statement
"the else" wont read the keyboard for a single character value whether i use scanf OR getchar. Can anyone spot a flaw? its an extremely simple code. thanks in advance.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch1;
char ch2;
char ch3;
int teger1;
int teger2;
int teger3;
printf("\tA. Me break you neck!\n\
\tB. Me electrocute you!\n\
\tC. Me kiss you!\n");
printf("Choose a task:");
ch1=getchar();
if (ch1=='A'||ch1=='a')
{
printf("CRRRACK!\n\n");
}
else if(ch1=='B'||ch1=='b')
{
printf("BZZZZZZZZT!\n\n");
}
else if(ch1=='C'||ch1=='c')
{
printf("MWAH!\x03\n\n");
}
else
{
printf("\t\tInvalid Entry!\n\t\tTry Again?");
printf("\n\n\t\tY/N");
//getchar(); /*<--input not being read...why?*/
scanf("%c",&ch2);
}
printf("\n\n");
system("pause");
return(0);
}
Im trying to get it to allow the user to select whether they want to try again or not.
The program runs fine with no errors it just doesn't prepare to read input. it just ends..?
update: the problem was that the enter key was being read right after the character i input.
Solution:
Code:
printf("\tA. Me break you neck!\n\
\tB. Me electrocute you!\n\
\tC. Me kiss you!\n");
printf("Choose a task:");
ch1=getchar();
getchar(); /*<----A stray getchar() absorbs the enter key so the next getchar() doesnt pick it up by mistake*/