I am reading books to improve my C++ and I wanted to try to get the leftover input from the input buffer after using the delimiter in getline(), this code works, it skips the cin statement and outputs the leftover buffer contents but my question is will it always do this? or is there a better way to do it?

 #include <iostream>
 #include <string>

using namespace std;

int main()
    string input;
    string leftoverInput;

    cout << "Enter some text" << endl;
    getline(cin, input, ',');

    cin >> leftoverInput;

    cout << input << endl;
    cout << leftoverInput << endl;

    return 0;
2 Years
Discussion Span
Last Post by NathanOliver

If you really want to clear out the input buffer then you should use Narue's code. Calling std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n'); should work almost always but as Narue mentions in her post there a a couple edge cases that will break it.


I dont want to clear the leftover contents i want to output the leftover contents.


To read everything that might be lingering in the buffer, you need to use the readsome function. Your current method just reads the next word, not the left-over data.

You could use something like this:

string leftoverInput;
char leftoverBuffer[64];
streamsize sz = 0;
do {
  sz = cin.readsome(leftoverBuffer, 64);
  leftoverInput.append(leftoverBuffer, sz);
} while( cin && (sz == 64) );

The point is that the readsome function will read data only until the current buffer is empty (or if there are more than the specified size to read). So, this loop reads 64 characters at a time, until there were less than 64 characters left on the buffer.


Oh. Oops. You could also do this using a string stream:

string leftoverInput
string temp;
stringstream ss;
while(getline(cin, temp))
    ss << temp;
leftoverInput = ss.str();

I am not sure if it would be any faster but you could also use just a couple strings:

string leftoverInput
string temp;
while(getline(cin, temp))
    leftoverInput += temp;
    // or

Edited by NathanOliver

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.