#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string name1, name2;
int age1 = 0, age2 = 0;
int dif = 0;
string ans;
bool stat = false;
while (stat == false)
{
cout << "Hello, what is your name and age? (separate with one space) ";
cin >> name1 >> age1;
if (age1 == NULL)
{
cout << "Give me a real age! ";
cin >> age1;
}
cout << name1 << ", what is your lover's name and age? ";
cin >> name2 >> age2;
if (age2 == NULL)
{
cout << "Give me a real age! ";
cin >> age2;
}
cout << name1 << "'s age is " << age1 << " and " << name2 << "'s age is " << age2 << "." << endl
<< "Is this correct? (YES or NO) ";
cin >> ans;
if (ans == "yes" || ans == "YES")
stat = true;
else
{
cout << endl << "Okay, let's try that again!" << endl << endl;
stat = false;
}
}
cout << endl << "This message means stat is true!";
return 0;
}
#include <limits>
...
cout << "Hello, what is your name and age? (separate with one space) ";
cin >> name1;
while (!(cin >> age1)) {
cout << "Give me a real age! ";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
It basically keeps looping until it reads a number. Each time it fails, it will ignore everything on the current line until the next line and clear any error flags