如何实现 throw 语句来执行整数值
How to implement throw statement to do a integer value
我有一个问题,对你们中的许多人来说可能很简单,但是,我还没有找到问题的答案。
我下面的程序运行正常。此代码将数字转换为浮点数和整数。
假设您输入了 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;
}
相关文章:
- 如何及时执行if语句?
- 获取上次执行的返回语句的行
- 如何仅在父循环的所有迭代都为真时才执行嵌套的 if 语句?
- 表单显示对话框函数错误,并且不执行下面的语句
- 如何知道调试时执行了哪个语句
- 在可变函数调用中执行一次语句
- 在多个对象上执行同一语句的零成本抽象
- 我怎样才能接受输入作为双精度值并执行 IF ELSE 语句
- c++:if 语句无法正常运行,并继续执行无效输出
- 为什么 cout 语句在传递指向函数的指针时没有执行?
- c++ IF 语句执行,但添加 ELSE 会显示错误
- C 程序如果功能中的语句不执行.在逻辑上似乎是错误的
- 当您希望在Arduino Uno编程中同时执行不同函数时,使用什么代码/语句
- OR 语句执行所有评估
- C++ Switch 语句在中断后执行
- C++ goto 语句执行而不调用
- 对条件语句执行逐位AND XOR
- 两个语句执行之间的时间差不一致
- 使用cout语句执行while循环
- 在c++中使用嵌套的if语句执行while循环