Jer*_*yRR 5 c++ error-handling exception-handling
我正在尝试编写一个提示用户输入五位数的函数,并且我想编写一个异常块来处理错误的输入,以防用户尝试输入字符串或某些非整数输入.
我知道如何为分割函数编写一个异常处理块,其中你抛出一个分母为0的异常,但我不知道如何对我无法控制的输入执行此操作.
首先,我通常会反对这一点 - 来自用户的错误输入几乎是规则而不是例外.
无论如何你坚持这样做,你可能会接受任何输入作为输入,然后在/如果它不是你想要的时候抛出异常:
// Warning: untested code.
// Accepting negative numbers left as an exercise for the reader.
int get_int(std::istream &is) {
std::string temp;
std::getline(temp, is);
for (int i=0; i<temp.size(); i++)
if (!isdigit(temp[i]))
throw std::domain_error("Bad input");
return atoi(temp);
}
Run Code Online (Sandbox Code Playgroud)
不过,我再说一遍,我认为这通常不是一个好主意.我注意到(例如)iostream已经fail为这种情况专门定义了一点(并且operator>>读取int 的法线使用了该机制).