[英]Input validation for reading in vector of ints
I'm reading in from the user a vector of ints and I'm trying to do some input validation so that if the user enters a letter it changes it to a 0. Here is what I have. 我正在从用户读取一个整数向量,并且尝试进行一些输入验证,以便如果用户输入字母,则将其更改为0。这就是我所拥有的。
for(int i=0; i < columns;i++)
{
int temp3;
cin >> temp3;
if (temp3 > 100 or temp3 < 0)
temp3 = 0;
if (isalpha(temp3)) //run-time error here
temp3 = 0;
newstu.push_back(temp3);
}
the commented line is the problem but since it's a run-time error. 注释行是问题所在,但由于它是运行时错误。 I'm not sure why this is wrong/doesn't work. 我不确定为什么这是错误的/不起作用。 Any ideas? 有任何想法吗? Thanks in advance 提前致谢
if you have access to boost, you could also try to use a try/catch design. 如果您有权使用增强功能,则还可以尝试使用“尝试/捕获”设计。
You have an example there: https://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast/examples.html 您在此处有一个示例: https : //www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast/examples.html
try
{
args.push_back(lexical_cast<int>(temp3));
}
catch(const bad_lexical_cast &)
{
args.push_back(0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.