How can I clear buffer between getch & cin?

Discussion in 'C++' started by voidstar, Jul 21, 2004.

  1. voidstar

    voidstar Guest

    Hi, I have the following problem:

    I use "getch" to monitor keypresses and the I use "cin" to input a

    When I type in 'y', the 'y' character appears, so I need to hit backspace
    before typing the string.

    c = getch();
    cin >> str;

    Please help me!
    Thanks in advance
    voidstar, Jul 21, 2004
    1. Advertisements

  2. getch is not part of standard C++, cin is part of standard C++. If you try
    an mix the two then the results are going to be unpredictable. Basically
    don't do it.

    Standard C++ has no way of monitoring keypresses, so if you need to do
    this then you should forget about using standard C++ for any console input
    or output.

    John Harrison, Jul 21, 2004
    1. Advertisements

  3. voidstar

    Ash Guest

    All true, but I found that it is compiler dependant. For example, in
    Borland's compiler:

    ch = getch();
    //select stuff
    cin >> string; //or even cin.getline(const char[], int)

    after pressing a button to be used in the switch() statement, that char
    would be placed at the beginning of the string's array. However, using
    Bloodshed's Dev-C++ IDE, it seems to 'clear the buffer'. I have, however
    heard of functions that do this. I think, but
    I'm not sure.
    Ash, Jul 27, 2004
  4. voidstar

    Mark R Rivet Guest

    I believe you should do a "cin>>ws;"
    the "ws" means white space and should clear the buffer after you do
    the getch();

    Mark R Rivet, Jul 27, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.