0

I'm using multiple getline(cin, string) calls to get two strings; however the code is skipping the second call and only handling the first.

for (int i = 0; i < 2; ++i)
{
    if (i == 0)
    {
        cout << "Please enter string A: " << endl;
        getline(cin, stringA);
    }

    if (i == 1)
    {
        cout << "Please enter string B: " << endl;
        cin.ignore();
        getline(cin, stringB);
    }
}

How do I change this to handle multiple getline() calls?

enter image description here

Paweł Mikołajczuk
  • 3,482
  • 23
  • 31
Daniel
  • 66
  • 9

2 Answers2

0

Unable to reproduce bad behaviour with the code given. Bug may be elsewhere.

Regardless, the code can be a lot simpler and that may solve other problems:

cout << "Please enter string A: " << endl;
getline(cin, stringA);
cout << "Please enter string B: " << endl;
cin.ignore(); 
getline(cin, stringB);

The for loop allows you to eliminate duplicated code by repeating the same code over with small differences in parameters. There is no duplicated code, so for does nothing for you here.

Not sure what the goal of the cin.ignore() line is. It will discard the first character of the second line of input. If that's what you want, groovy if not, reconsider.

user4581301
  • 29,019
  • 5
  • 26
  • 45
0

It looks like you are calling some form of cin >> someString; earlier in the code.

If so, it has probably left a newline in the input stream. Thus when the first getline() is called it will immediately stores this newline in stringA then waits for input for stringB. Consider either using getline() for all your inputs, or calling a "dummy" getline() after each time you use cin >> ...;. This dummy getline() will clear the input stream, avoiding this type of bug.

Patrick vD
  • 527
  • 5
  • 21
  • [Why does std::getline() skip input after a formatted extraction](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Remy Lebeau Oct 03 '20 at 23:07