如何实现 throw 语句来执行整数值

How to implement throw statement to do a integer value

本文关键字:语句 执行 整数 throw 何实现 实现      更新时间:2023-10-16

我有一个问题,对你们中的许多人来说可能很简单,但是,我还没有找到问题的答案。

我下面的程序运行正常。此代码将数字转换为浮点数和整数。

假设您输入了 5.4,程序将为您提供 5.4 的双精度和 5 的整数。

现在我需要在我的程序中添加一个 throw catch 语句,以防用户输入文本而不是数字("如果转换失败,抛出异常并允许用户重新输入值。

这是我需要做的伪代码。

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

我实现了这样的东西,但它没有奏效。我设置了"a"变量字符,认为用户必须输入文本才能获得该消息。但是它不起作用并给出了一些错误。

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  
    }

我对这个"尝试,投掷,接住"术语很陌生。 如果你能帮我解决这个问题,我会很高兴,谢谢。

#include <C:\CSIS1600MyCppUtils.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;
    }
} 

您可以使用 Boost 进行词法转换。 如果您有有效的输入(例如 2.54),则不会抛出异常,但输入无效(例如 2???54)抛出bad_lexical演员表:

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