I tried to make a program that takes the inputs until the -1 is entered and handles the inputs properly using exceptions.
It takes user inputs FirstName
and Age
and print the FirstName
and increased age by 1. If the second variable is not an integer(age) then it should print FristName
and 0
.
But my program gives me an unexpected output. How can I fix this?
Thanks in advance.
Input format
John 12
Michel 15
Alice Graz 11
Bob 15
-1
Expected Output
John 13
Michel 16
Alice 0
Bob 16
My code
#include <string>
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string inputName;
int age;
cin.exceptions(ios::failbit);
cin >> inputName;
while (inputName != "-1")
{
try
{
cin >> age;
}
catch (exception ex)
{
age = -1;
if (cin.fail())
cin.clear();
cin.ignore();
}
cout << inputName << " " << (age + 1) << endl;
cin >> inputName;
}
return 0;
}
try using cin.ignore()
like this
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You have to include <limits>
header file.
Thanks that works. but there's a warning warning: catching polymorphic type ‘class std::exception’ by value [-Wcatch-value=] catch (exception ex)
can you just explain what that line does and why passing such a numeric_limit together with '\n'. Thanks
try this catch statement instead
catch(std::ios_base::failure& faill)
you can refer this cplusplus.com/reference/istream/istream/ignore
Thank you very much.