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;
}

Recommended Answers

All 4 Replies

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
    leftoverInput.append(temp);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.