有没有办法捕获 STL 函数未被赋予正确参数的异常?

Is there a way to catch the exception of an STL function not being given right arguments?

本文关键字:参数 异常 STL 函数 有没有      更新时间:2023-10-16

我正在使用std::stol((将字符串转换为长类型。但是,如果用户输入字母,如何确保捕获异常?

代码可以在这里找到。

注意:我已经找到了这个问题的正确方法,我只需要知道该怎么做,而不是:

if ( !(stol(input)) ) // Yes, I know it's stupid to think the output would be bool
throw 'R'; 
std::stol()

输入错误时引发异常。使用try..catch来捕捉它们。

从评论到另一个答案,这里的目标似乎有些模棱两可。为了回答标题中的问题,为了捕获异常,您编写了一个try ... catch块:

long get_value() {
for (;;) {
std::cout << "Enter a number: ";
std::string text;
std::cin >> text;
try {
return stol(text);
} catch(...) {
std::cout << "Invalid inputn";
}
}
}

但评论表明,扫描整个输入文本以查看任何地方是否有字母的解决方案是合适的。如果目标是要求输入仅包含数字,则无需在调用std::stol之前扫描每个字符。它比你想象的更聪明。

int last;
std::stol(text, &last);
if (last != text.length())
// got a bad character

这将检测类似"123q"的输入。

与往常一样,请阅读文档