Exception handling to detect input string vs. integerThe given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. The program fails and throws an exception if the second input on a line is a string rather than an integer. At FIXME in the code, add try and except blocks to catch the ValueError exception and output 0 for the age.Ex: If the input is:Lee 18Lua 21Mary Beth 19Stu 33-1then the output is:Lee 19Lua 22Mary 0Stu 34IN PYTHON PLEASE

Respuesta :

DALAU

Answer:

Please find the answer below.

Please do comments in case of any issue. Also, don't forget to rate the question. Thank You So Much.

main.cpp

#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main(){

  //string for input

  string input;

  //index to store all input

  int index=0;

  //to store all names

  string names[100];

  //to store all ages

  int ages[100];

  //to store age

  int age;

  //to get name

  string name;

  while(true){

      age = -999;

      //read line input

      getline(cin,input);

      //convert to stream

      stringstream ss(input);

      //get name and age

      ss>>name>>age;

      //if name is -1 break the loop

      if(name=="-1"){

          break;

      }

      if(age!=0){

          age++;

      }

      names[index] = name;

      ages[index] = age;

      index++;

  }

  cout<<"OUTPUT is as below"<<endl;

  for(int i=0;i<index;i++){

      cout<<names[i]<<" "<<ages[i]<<endl;

  }

  return 0;

}

Ver imagen DALAU
ACCESS MORE