[英]Verifying data type during parsing (string to int) in c++
我正在尝试测试将字符串强制转换为整数,以确保字符串中的数据实际上是属于整数的数据。 (例如,用户输入“ !!!!”,因此我不希望它进入int)。
我遇到的问题是我希望能够在检测到无法发生转换后立即以某种方式引发错误。 我想在转换期间或之后进行测试的原因是因为我需要用户输入才能首先进入字符串。
我首先尝试执行“选项1”,但我注意到弹出了一些调试错误,它不允许我自己抛出错误并显示更多用户友好的错误。
然后,我尝试使用选项2(认为我可以将验证内容包装在强制类型转换周围),但是当我看着变量类型时,即使它显示为字符串并且我的代码似乎也没有抓住它,但它还是通过了选项2。诠释,因此抛出我的错误
我将只使用两个选项之一,并同时注意两个。 我只是把我的两个
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");
}
为了测试一个值,我提供了正则表达式:
#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;
}
露宿者的想法一点也不坏。 但是,我们也可以捕捉到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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.