我试图将字符串转换为整数,以确保字符串中的数据实际上是属于整数的数据。 (例如,用户输入' !!!!'所以我不想让它进入int)。
我遇到的问题是我希望能够在检测到转换无法发生后立即抛出错误。我想在演员阵容期间或之后测试它的原因是因为我需要用户输入首先转到字符串。
我首先尝试做"选项1"并且我注意到会弹出某种调试错误,并且它不会让我自己抛出并显示更加用户友好的错误。
然后我尝试选项2(认为我可以在演员周围包装验证)但是当我观察变量类型时,它会传递选项2,即使它显示为字符串和我的代码似乎没有发现它不是一个int,因此抛出我的错误
我只会使用这两个选项中的一个,并且显然都要注意。我只是放了我的两个
using namespace std;
#include <string>
#include <iostream>
#include <typeinfo>
int main()
{
string employeeNumber;
string hoursWorked;
int newEmployeeNumber;
cout << "What is your employee number?" << endl;
cin >> employeeNumber;
//CONVERT AND VERIFY CAST/CONVERSION OCCURRED SUCCESSFULLY
//IF NOT (ex. user entered '!!!' so it shouldnt be able to cast to int..
//THEN THROW MY ERROR
//option 1
newEmployeeNumber = stoi(employeeNumber);
throw MyErrorThatDoesntGetReached("notan int");
//(will throw its own error right there and I can't let it throw mine after
//option 2
if (typeid(stoi(employeeNumber)) != typeid(int) )
throw Exception("data in file is CORRUPT");
}
答案 0 :(得分:0)
为了测试一个值,我提供了正则表达式:
#include <string>
#include <conio.h>
#include <iostream>
#include <typeinfo>
#include <regex>
using namespace std;
bool isNumber( string val );
void main() {
string employeeNumber;
string hoursWorked;
int newEmployeeNumber;
cout << "What is your employee number?" << endl;
cin >> employeeNumber;
if ( isNumber( employeeNumber ) ) {
newEmployeeNumber = stoi(employeeNumber);
cout << "is number\n";
}
else {
cout << "is not number\n";
}
getch();
}
bool isNumber( const string val ) {
std::string templ("\\d*");
if ( regex_match( val, std::regex(templ) ) ) {
return true;
}
return false;
}
更新: 函数IsNumber的其他变体:
bool isNumber( const string val ) {
for( int i = 0; i < val.length(); i++ ) {
if ( !isdigit( val[i] ) ) {
return false;
}
}
return true;
}
答案 1 :(得分:0)
睡眠者的想法一点也不差。或者,我们可以捕获std::stoi()
抛出无效输入的异常:
#include <string>
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
string employeeNumber;
string hoursWorked;
int newEmployeeNumber;
cout << "What is your employee number?" << endl;
cin >> employeeNumber;
try {
newEmployeeNumber = stoi(employeeNumber);
} catch (std::invalid_argument const & e) {
throw MyException("The input couldn't be parsed as a number");
} catch (std::out_of_range const & e) {
throw MyException("the input was not in the range of numbers supported by this type");
}
}