Help C/C++ starter

Thread Starter

chrischristian

Joined Feb 22, 2008
43
I want to make a progamme of quiz format given:


#include<stdio.h>
#include<ctype.h>
main()
{
char character,character1;
clrscr();
{
printf("WHO INVENTED THE LIGHT BULB?\n");
printf("(a) Thomas Edison (b) Gerarled Philips\n");
printf("(c) Nicolous Tesla (d) Volta\n");
character=getchar();
if(character== 'a')
printf("YOUR ANSWER IS RIGHT!\n");
else
printf("SORRY!\n");
}
printf("end\n");
{
printf("WHO INVENTED THE LIGHT BULB?\n");
printf("(a) Thomas Edison (b) Gerarled Philips\n");
printf("(c) Nicolous Tesla (d) Volta\n");
character1=getchar();
if(character1== 'a')
printf("YOUR ANSWER IS RIGHT!");
else
printf("SORRY!");
}
switch(getch())
case 'x': exit();
return 0 ;
}


(Ignore that both quastions are same, they can be different too.)

Now, the problem with the programme is that it runs well only up to one quastion and answer only and after finishing the checking of the first answer ( RIGHT or SORRY) it print the second quastion and without scaning it's response it directly deliver (""SORRY") message which supposed to be only after saning and checking the answer only, so, please some one help me!!
 

rwmoekoe

Joined Mar 1, 2007
172
it is because the buffer still had another character (definitely not an 'a' in that case), and the second time getchar() was called returned that character.

you may want to use the function _getch() instead. it reads a single character at a time and returns right after that.
 

Thread Starter

chrischristian

Joined Feb 22, 2008
43
Thankyou rwmoekoe!!
That solved the problem but, I am confused that what do you mean by "buffer", does that mean the getchar function read character continiously except the privious ones?
 

chesart1

Joined Jan 23, 2006
269
I've run your program in C-Free and received the exact same results.

The function getchar() uses a line-buffered input. Unfortunately characters may be left in the buffer. In your program, the ENTER key was left in the buffer in the first loop. When getchar() is called in the second loop, it already sees the ENTER key in the buffer and does not wait for another entry.

I've tried getche() and received the same results. S Lannan has the best suggestion: using fflush().

The book C++ The Complete Reference suggests you use cscanf() or cgets().
 
Top