Reputation: 79
The following code is not working properly. scanf and printf statements in the ques2() function are not working in execution. please help me with it.
void main()
{
printf("\t\t\t\t\tKBC");
ques1();
}
void ques1()
{
char c;
printf("\nQ1 WHAT IS THE CAPITAL OF INDIA?");
printf("\na. Delhi \tb. Kolkata");
printf("\nc. Rome \td. China\n");
scanf("%c",&c);
if(c=='a')
{
ques2();
}
else printf("wrong answer");
}
ques2()
{
printf("ques2");
char d;
scanf("%c",&d);
printf("%c",d);
ques3();
}
ques3()
{
printf("ques3");
char d;
scanf("%c",&d);
printf("%c",d);
}
Upvotes: 0
Views: 90
Reputation: 79
I got another answer to the question. There is another method of clearing memory of the buffer i.e fflush(stdin) before scanf statement
this function clears anything that is in the buffer and then allow us to use scanf simply.
Upvotes: 0
Reputation: 206567
When you use:
scanf("%c",&c);
the newline character is still left in the input stream after the character is read. Next time such a statement is used, the newline character is read into c
. If you want to skip leading whitespaces, replace the format in those to " %c"
.
scanf(" %c",&c);
Make that change in ques1
, ques2
, and ques3
.
Update, in response to OP's comment
When you use
scanf("%c",&c);
If your type a
followed by Enter, then the first scanf
stores 'a'
in c
. The second scanf
stores a '\n'
in c
.
When you use
scanf(" %c",&c);
all leading whitespace characters are skipped. Hence, the '\n'
from the input stream is not read into c
.
Upvotes: 2