Question

In C++ Please

The given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incre

main.cpp Load default template.... 1 #include <string> 2 #include <iostream 3 4 using namespace std; 5 6 int main(int args, c

main.cpp Load default template... 7 int age; 4 using namespace std; 5 6 int main(int args, char argv[]) { string inputName; 9

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution - The required modified code in C++ is given below -

#include <bits/stdc++.h>
using namespace std;

int main(int argc, char* argv[]){
   string inputName;
   int age;
   bool flag = true;
   //set exception mask for cin stream
   cin.exceptions(ios::failbit);
   cin>>inputName;
   while(inputName != "-1"){
       //using try and catch handling the exception for second input as string
       //and setting the age to -1

           try{
                   cin >> age;
                   flag = true;
           }
           catch(std::ios_base::failure &fail) {
                   flag = false;
                   cin.clear();
                   std::string tmp;
                   getline(cin, tmp);
              age = -1;
           }
       cout<<inputName<<" "<<(age+1)<<endl;
       cin>>inputName;
   }
   return 0;
}

Explanation -

  1. In this code i inserted try/catch to catch the exception of string instead of int.
  2. Cleared cin's failbit and put cin in usable state using cin.clear().
  3. In catch, age is set to -1, so the final output will be age = 0 for this exception.
  4. The rest of the code is same. I have added only the required part.

Refer to the screenshot below for code and output -

#include <bits/stdC++.h> using namespace std; int main(int argc, char* argv[]) { string inputName; int age; bool flag = true;

Add a comment
Know the answer?
Add Answer to:
In C++ Please The given program reads a list of single-word first names and ages (ending...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Exception handling to detect input String vs. Integer

    6.6 LAB: 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 a try/catch statement to catch java.util.InputMismatchException, and output 0 for the age.Ex: If the input is:Lee 18 Lua 21 Mary Beth 19 Stu 33 -1then the output...

  • Write a program that reads a list of integers ending with a negative, and that then...

    Write a program that reads a list of integers ending with a negative, and that then outputs that list in reverse. After the negative that ends the list, a character indicates what character should separate the output integers. If the input is: 3 5 2 - 1 * the output is: 2*5*3 LAB ACTIVITY 7.16.1: LAB: Reverse a list, with separating characters 2 / 10 main.cpp Load default template... 6 7 8 int numbers [100],i=0, num, size; char character; cin>>num;...

  • Write a program that Reads a string from cin Prints the first and last letter without...

    Write a program that Reads a string from cin Prints the first and last letter without space in between, followed by endl For example, For an input seattle your program prints se(endl). For an input newyork your program prints nk (endl). You can assume that the length of the string is always greater than 1. LAB 0/10 ACTIVITY 1.9.1: Week2-4 Zip main.cpp Load default template. #include <iostream> using namespace std; 4int mainO 6 /* 8return Type your code here. /...

  • First create the two text file given below. Then complete the main that is given. There...

    First create the two text file given below. Then complete the main that is given. There are comments to help you. An output is also given You can assume that the file has numbers in it Create this text file: data.txt (remember blank line at end) Mickey 90 Minnie 85 Goofy 70 Pluto 75 Daisy 63 Donald 80 Create this text file: data0.txt (remember blank line at end) PeterPan 18 Wendy 32 Michael 28 John 21 Nana 12 Main #include...

  • In C++ please. 7.26 LAB: Nutritional information (classes/constructors) Given main(), complete the Food Item class (in...

    In C++ please. 7.26 LAB: Nutritional information (classes/constructors) Given main(), complete the Food Item class (in files Foodltem.h and Fooditem.cpp) with constructors to initialize each food item. The default constructor should initialize the name to "None" and all other fields to 0.0. The second constructor should have four parameters (food name, grams of fat, grams of carbohydrates, and grams of protein) and should assign each private field with the appropriate parameter value. Ex: If the input is: M&M's 10.0 34.0...

  • The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried t...

    The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried to divide the code in 3 parts (Patient.h, Patient.cpp and Main.cpp), but it is giving me errors. Patient.h #ifndef PATIENT_H #define PATIENT_H #include <string> #include "Patient.cpp" using namespace std; class Patient{ private : string firstname; string lastname; string location; static int cnt; int id; public : Patient(string, string, string);...

  • LW: Class Constructors Objectives Write a default constructor for a class. Note that this const...

    LW: Class Constructors Objectives Write a default constructor for a class. Note that this constructor is used to build the object anytime an argument is not provided when it is defined. Write a parameterized constructor that takes arguments that are used to initialize the class’s member variables Labwork Download the code associated with this lab: ColorConstructor.zip Main.cpp Color.h Color.cpp Compile and run the code. The first line of output of the program should display nonsensical integers for the values of...

  • C++ how can I fix these errors this is my code main.cpp #include "SpecialArray.h" #include <...

    C++ how can I fix these errors this is my code main.cpp #include "SpecialArray.h" #include <iostream> #include <fstream> #include <string> using namespace std; int measureElementsPerLine(ifstream& inFile) {    // Add your code here.    string line;    getline(inFile, line);    int sp = 0;    for (int i = 0; i < line.size(); i++)    {        if (line[i] == ' ')            sp++;    }    sp++;    return sp; } int measureLines(ifstream& inFile) {    // Add your code here.    string line;    int n = 0;    while (!inFile.eof())    {        getline(inFile,...

  • in c++ please include all of the following " template class, template function, singly linked list,...

    in c++ please include all of the following " template class, template function, singly linked list, the ADT stack, copy constructor, operator overloading, "try catch"and pointers Modify the code named "Stack using a Singly Linked List" to make the ADT Stack that is a template class has the code of the destructor in which each node is directly deleted without using any member function. As each node is deleted, the destructor displays the address of the node that is being...

  • In C++: Please help me correct this code .... All parts with (FIX ME) #include <algorithm> #include <climits&gt...

    In C++: Please help me correct this code .... All parts with (FIX ME) #include <algorithm> #include <climits> #include <iostream> #include <string> // atoi #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ const unsigned int DEFAULT_SIZE = 179; // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() {...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT