C++ Zybook Lab 16.5 LAB: Exception handling to detect input string vs. int The given program reads...

90.2K

Verified Solution

Question

Programming

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;
}

Answer & Explanation Solved by verified expert
4.2 Ratings (572 Votes)
Please look at my code and in case of indentation issues checkthe screenshotsmaincppinclude include    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students