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,692
  • 25
  • 32
Daniel
  • 66
  • 1
  • 9

3 Answers3

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
  • 33,082
  • 7
  • 33
  • 54
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
  • 684
  • 1
  • 7
  • 24
  • [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
-1

have you been declared strings before it because it is working properly in my

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 09 '22 at 21:51