Help C/C++ starter

Discussion in 'Programmer's Corner' started by chrischristian, Mar 15, 2008.

  1. chrischristian

    Thread Starter Active Member

    Feb 22, 2008
    43
    0
    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!!
     
  2. rwmoekoe

    Active Member

    Mar 1, 2007
    172
    0
    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.
     
  3. chrischristian

    Thread Starter Active Member

    Feb 22, 2008
    43
    0
    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?
     
  4. S_lannan

    Active Member

    Jun 20, 2007
    247
    2
    after using scanf or getchar functions i just put
    fflush(stdin);
    after them and that clears the buffers
     
  5. chesart1

    Senior Member

    Jan 23, 2006
    269
    1
    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().
     
Loading...