CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 2 of 2

Thread: Clear cin Buffer

  1. #1
    Join Date
    Jun 2009

    Clear cin Buffer

    I am having a hell of a time trying to clear the cin buffer.

    I have a loop in my program that waits til you press a specific key, but during that time if you are pressing random letters etc, once you hit the key and it then goes to my cin statement, all those random letters and numbers you pressed are there, including the enter button for a new line.

    Ive read some threads and googled it

    tried cin.clear(), cin.ignore(), cin.ignore(1000, '\n'); and a few other combinations with different inputs in ignore();

  2. #2
    Join Date
    Jun 2009

    Re: Clear cin Buffer

    cin doesn't work that way. cin is a stream, and as such, has no knowledge of things like "keys", let alone key presses... All it knows are that it holds chains of characters it can parse. At best, you can try to read cin, and if you see the character 'a', you can deduce the user pressed the key a... You can forget about things like arrow keys, control keys, simultaneous presses etc...

    Another problem with cin (on a classic os), is that once it is out of buffer and requires user input, the program halts until you have written all your input, and pressed the enter key (on a classic os). That means that even if all it needed was a single char, it will wait until you are done writing.

    The best solution (IMO), would be to use OS specific libraries (like windows.h), or an abstract wrappers, that have handles to actual keyboard presses.

    In short, it is very difficult (if not impossible) to have the program be informed of a keypress immediately, using streams
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)