Getting leftover string contents from input buffer

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #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;
}
No. Line 14 gets a single sequence of non-whitespace characters:

Hello, World!\n outputs
Hello
World
and '\n' is left in input buffer.
Hi, how are you?\n outputs
Hi
how
and are you?\n is left in input buffer.
What,\n will output What and will request user to enter more text.

If you are working in dialog mode and input is line-buffred, best approach is to use .ignore():
1
2
3
#include <limits>
//...
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Last edited on
ok, what is dialog mode?
Your usual console prompts when working with human.
oh ok, well i dont want to get rid of leftover input, i want to output it.
So instead you want to read input left until line end? Use std::getline:

std::getline(std::cin, leftover_input);
Topic archived. No new replies allowed.