0

I am learning C++.

I wrote a simple C++ programme to take in my name, my age, my wife's name, and my wife's age and print it on screen. This is the code:

#include <iostream>

using namespace std;

void myFunction();


int main() {
  myFunction();

  return 0;
}

void myFunction() {

  string hName;
  string wName;
  int hAge;
  int wAge;  

  cout << "Please enter your name:" << endl;

  getline(cin, hName);

  cout << "Enter your age:" << endl;

  cin >> hAge;

  cout << hName << " is " << hAge << " years old." << endl;

  cout << "\nPlease enter your wife's name:" << endl;

  getline(cin, wName);

  cout << "\nPlease enter your wife's age:" << endl;

  cin >> wAge;

  cout << wName << " is " << wAge << " years old." << endl;
}

I made the file:

make filename.cpp

And I ran the binary:

./filename

And this is the weird output:

Please enter your name:
Basil Ajith
Enter your age:
30
Basil Ajith is 30 years old.

Please enter your wife's name:

Please enter your wife's age:
Alfia Abubaker
 is 0 years old.

Right after I enter my name and age and the sentence is printed out, both sentences that prompt me to enter my wife's name and age are printed together. I enter my wife's age and the last line

 is 0 years old.

is printed and the programme exits.

Why this strange behaviour?

Basil Ajith
  • 105
  • 8
  • 1
    Possibly relevant (duplicate) questions: [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/q/21567291/580083), [cin and getline skipping input](https://stackoverflow.com/q/10553597/580083). – Daniel Langr Jul 31 '20 at 11:43
  • 1
    Using both `>>` and `getline`, like that, will not work the way you think it will work. See the linked question for more information. – Sam Varshavchik Jul 31 '20 at 11:44
  • 1
    Most common C++ question on stack overflow, by some distance. – john Jul 31 '20 at 12:06
  • Sorry, I only did a cursory search for duplicate questions. – Basil Ajith Aug 04 '20 at 10:05

0 Answers0