Question

I have a question that might be very simple to many of you however, I have not found an answer to my question.

I have the program below that is working properly. This code turns a number into a floating number and integer.

Let's say you entered 5.4, the program will give you 5.4 for double and 5 for integer.

Now I need to add a throw catch statement to my program in case the user enters a text instead of a number ("If the conversion fails, throw an exception and allow the user to re-enter the value.").

This is the pseudocode of what I need to do.

try {
        if(num ==character)
            throw;
        cout << "\n The number entered " << num << "invalid, please enter again";
    }
    catch
    {
    }

and I implemented something like this, however it did not work. I set the 'a' variable character thinking the user has to enter a text in order to get that message. However it did not work and gave some errors.

try
    {
      char a;
      if (num == a) 
        throw num;  
    }
    catch(int e)
    {
      cout << "A number of " << a << " is invalid." << endl;
      cout << "Please re-enter a number: ";
      cin << num  
    }

I am very new with this "try,throw,catch" terms. I would be happy if you help me through this, thanks.

#include <C:\\CSIS1600\MyCppUtils.cpp>
#include <iostream>
#include <string>
using namespace myNameSpace;
int main()
{   
    runner("is running");
    cout << "Enter a number :  ";
    string num;
    getline(cin, num);

    cout<< "double " << getValidDouble(num) << endl;
    cout<< "integer " << getValidInt(num) << endl;

    system("pause");
    return 0;
}

#include<iostream>
#include<string>
using namespace std;

namespace myNameSpace
{
    string num;

    void runner(string str)
    {
        cout <<"runner-3() is running.."<<endl;
    }

    int getValidInt(string n)
    {

        int valueint;
        valueint=atoi(n.c_str());
        return valueint;
    }

    double getValidDouble(string n )
    {

        double valuedouble;
        valuedouble = atof(n.c_str());
        return valuedouble;
    }
} 
Was it helpful?

Solution

You can use Boost to do a lexical cast. If you have valid input (e.g. 2.54), no exception will be thrown, but with invalid input (e.g. 2???54) the bad_lexical cast is thrown:

#include <boost/lexical_cast.hpp>

try
{
    double x1 = boost::lexical_cast<double> ("2.54");
    double x2 = boost::lexical_cast<double> ("2???54");
    cout << x1 << x2 << endl;
}
catch(boost::bad_lexical_cast& e)
{
    cout << "Exception caught - " << e.what() << endl;
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top