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?