0

I'm new in C++ and I'm trying to catch an input value from console and assing it to a string variable. I don't know why at the first loop doesn't wait but at the second it does.

Here is the relevant code:

bool success = false;
string name;
string txtAge;
short age;
while (!success) {
    cout<<"Person name: \n";
    getline(cin,name);
    cout<<"Person age: \n";
    getline(cin, txtAge);
    try {
        age = lexical_cast<short>(txtAge);
        Person newPerson(nombre, edad);
        personList->Add(&newPerson);
        success = true;
    }
    catch (...) {
        cout << "Error message\n";
        system("pause");
    }
}

If anyone knows why is this happening and want to say it,I would be grateful for it. Have a nice day.

  • What are the inputs to your program, and what outputs do you expect? Also, `personList->Add(&newPerson);` is almost certainly a bug. The address that you are passing in to `personList` is about to become invalid. – cigien May 25 '20 at 17:48
  • Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – BessieTheCookie May 25 '20 at 17:48
  • 3
    Please post a [mre] next time. Your problem is related to code that you didn't show, and I'm only able to identify it because it happens to be a common problem that I've seen countless times before. – BessieTheCookie May 25 '20 at 17:50
  • @cigien That's just a method, which is a void, of my program. The only thing I didn't paste is the signature. personList it's a list pointer that I send as a parameter. If I add a person to the list manually (creating people and adding at the main method) there's no problem. My problem is that when the first loop goes, it doesn't stop in getline() methods but it stops in second loop. – Bruno Gonzalez Torres May 25 '20 at 23:57

0 Answers0