0

I have a C++ program. I want to get a number from the user (t) and force the user to enter line t times but the program's execution terminates after 1 iteration. This is the code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    int t;
    cin >> t;
    for (int i=0; i< t; i++) {
        getline(cin, str);
        cout << str;
    }
    return 0;
}

Can anyone explain me why this happening and how to solve it? Thank you my friends.

CoderCharmander
  • 1,602
  • 8
  • 15

2 Answers2

3

The newline character is still in the buffer when you do cin >> t so the next line you read will be blank. When you mix formatted input (>>) and unformatted (std::getline) you often get in situations like this and you need to take measures when switching to unformatted input. Example remedy:

#include <iostream>
#include <limits>
#include <string>

using namespace std;

int main() {
    string str;
    int t;
    cin >> t;
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // skip the rest of the line

    for(int i = 0; i < t; i++) {
        if(getline(cin, str))    // check that the getline actually succeeded
            cout << str << '\n';
        else
            break;
    }
    return 0;
}
Ted Lyngmo
  • 37,764
  • 5
  • 23
  • 50
2

When you enter your first character (the times to repeat), a character is left in the cin buffer - newlines are not consumed by cin >>. As a result, getline(cin, str) reads this character and takes it as the first input, which then empties the buffer out and lets you enter the others.

You can clear the buffer with std::cin.ignore(1); to remove that trailing character - this lets your code run as anticipated. Why not just use cin >> str, though? That solves the problem and avoids a call to getline.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;
    int t;
    cin >> t;

    //clear one character out of buffer
    cin.ignore(1);

    //note that 1 is used for demonstration purposes
    //in development code, INT_MAX, numeric_limits<streamsize>::max(),
    //or some other large number would be best, followed
    //by std::cin.clear()

    for (int i=0; i< t; i++) {
        cout << "input: ";
        //you could use cin >> str; instead of getline(cin, str);
        getline(cin, str);
        cout << "got: " << str << std::endl;
    }
    return 0;
}

Demo

Nick Reed
  • 5,029
  • 4
  • 14
  • 34