C++ Zybook Lab 16.5 LAB: Exception handling to detect inputstring vs. int
The given program reads a list of single-word first names andages (ending with -1), and outputs that list with the ageincremented. The program fails and throws an exception if thesecond input on a line is a string rather than an int. At FIXME inthe code, add a try/catch statement to catch ios_base::failure, andoutput 0 for the age.
Ex: If the input is:
Lee 18Lua 21Mary Beth 19Stu 33-1
then the output is:
Lee 19Lua 22Mary 0Stu 34
Here's the code:
#include
#include
using namespace std;
int main(int argc, char* argv[]) {
string inputName;
int age;
// Set exception mask for cin stream
cin.exceptions(ios::failbit);
cin >> inputName;
while(inputName != \"-1\") {
// FIXME: The following line will throw an ios_base::failure.
// Insert a try/catch statement to catch the exception.
// Clear cin's failbit to put cin in a useable state.
try{
//Reading age
cin >> age;
//Printing Name and age incremented by 1 if correct values areentered
cout << inputName << \" \" << (age + 1) <}
catch(ios_base::failure){
//Clear cin
cin.clear();
}
 Â
cin >> age;
cout << inputName << \" \" << (age + 1) <cin >> inputName;
}
return 0;
}