-4

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.

Evan Wild
  • 47
  • 4
  • 2
    Please show your code. How else do you expect us to help spot the error? – Johnny Mopp Jan 18 '19 at 00:26
  • Just added some example code – Evan Wild Jan 18 '19 at 00:36
  • This works for me: https://onlinegdb.com/B1yqWiCf4 – Jerry Jeremiah Jan 18 '19 at 00:45
  • @EvanWild to help going forward, you can do this in about 4 lines of code. If you read with `while (getline (std::cin, line))`, then just create a `stringstream` to read each word, check its `length`, and then `find` and `replace`, e.g. `std::string word; std::stringstream s (line); while (s >> word) if (word.length() == 4) line.replace (line.find (word, 0), 4, repl);` (with `const std::string repl = "****";` defined before hand) – David C. Rankin Jan 18 '19 at 01:42

1 Answers1

0
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;
}
Andreas DM
  • 9,654
  • 6
  • 31
  • 58