Search code examples
c++stringinputgetline

How to force getline() to input one line at a time


I need to input a certain number of strings, each one entered on a new line. When I try to use getline() in a loop, it inputs the first string then ends immediately.

Here's the problem I'm trying to solve, where you can see the style of input I'm going for: https://wcipeg.com/problem/ccc98s1

I've looked at cin.ignore() to fix the problem, but I can't seem to get it working right.

int n;
cin >> n;

for(int i = 0; i < n; i++) {
    string input;
    getline(cin, input);
    cout << "Line Entered: " << input << endl;
}

If you enter 2 for n, then try to enter two strings on separate lines then it does not work.


Solution

  • int n;
    cin >> n;
    cin.ignore(); // are you sure you tried this?
    
    for(int i = 0; i < n; i++) {
        string input;
        getline(cin, input);
        cout << "Line Entered: " << input << endl;
    }