Clearing c++ input buffer

This is a discussion on Clearing c++ input buffer within the C++ Programming forums, part of the General Programming Boards category; Ok, I want to clear the input buffer of any data that is over the the size of my character ...

  1. #1
    Or working on it anyways mramazing's Avatar
    Join Date
    Dec 2005
    Location
    Lehi, UT
    Posts
    121

    Clearing c++ input buffer

    Ok, I want to clear the input buffer of any data that is over the the size of my character array.
    I have tried using cin.ignore() and cin.ignore(20, '\n' and cin.clear (though im not fully aware of how cin.clear()) works.
    Code:
        cin.clear();
        cin.ignore(20, '\n');
        cin.get();
        cout << cin.get() << endl;
    Is there anyway i can fix this or make it so crap after the my character array is thrown away?

    THANK YOU !!!
    -- Will you show me how to c++?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Why not use a std::string?
    Code:
    std::string buffer;
    
    getline(cin, buffer);

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    But if you must use a char array, a clear() followed by an ignore() will work:
    Code:
        cin.clear();
        cin.ignore(80, '\n');

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >though im not fully aware of how cin.clear()) works.
    clear will reset the stream state flag. It doesn't extract any characters, but if the state is an error, clearing it will allow you to read from the stream again. This link goes into detail about how to flush the input stream buffer.
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    If you want to make sure you ignore all data in the buffer, you might consider a larger number than 20 or 80.
    Code:
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    That's a commonly used version that will pretty much discard everything in the input stream up to and including the newline. You need to #include <limits> for numeric_limits and <ios> for streamsize.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 04:25 PM
  2. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  3. Clearing the input stream
    By abh!shek in forum C Programming
    Replies: 10
    Last Post: 05-18-2008, 04:50 PM
  4. How to put a Char into the Input buffer of a console?
    By Aidman in forum C++ Programming
    Replies: 10
    Last Post: 03-09-2003, 10:05 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21