如果有人输入文本而不是数字,C ++如何捕获异常? [英] C++ how can I catch an exception if someone enters text instead of a number?
问题描述
我正在尝试让某人输入介于-1和122之间的数字.我想使用throw,catch并尝试是否有人输入了char或string而不是数字.如果那是最好的方法?
I''m trying to get someone to enter a number between -1 and 122. I want to use throw, catch and try if someone enters a char or string instead of a number. If that''s the best way to do it?
#include <iostream>
using namespace std;
int main()
{
int age;
int x = 0;
int y = 121;
cout << "Enter you age: ";
cin >> age;
if (age >= x && age <= y)
cout << "So your age is: " << age << ", that''s believable";
else
cout << "Your age is " << age << "? Not Believable!";
return 0;
}
我尝试过的事情:
我尝试过投掷,接住,尝试的方法,但是我不够有知识,无法正确编码.
What I have tried:
I''ve tried to play around with throw, catch, try but I''m not knowledgeable enough to code it right.
推荐答案
您需要阅读输入内容作为文本字符串,然后检查它的有效字符.cin
方法将只读取字符,直到找到一个非数字并返回可以从输入的任何数字转换而来的任何值.
[edit]
以下Jochen的建议是一个更好的主意.
[/edit]
You need to read the input as a text string and then examine it for valid characters. Thecin
method will merely read characters until it finds a non-digit and return whatever value can be converted from any digits entered.
[edit]
Jochen''s suggestion below is a better idea.
[/edit]
输入了输入后,请使用 ios: :fail-C ++参考a> [ ^ ]标志以检查输入的数字是否有效:
After the input has been entered use the ios::fail - C++ Reference[^] flag to check if the input was a valid number:
cin >> age;
if (std::cin.fail())
// report not a number
else if (age < 0 || age > 122)
// report invalid range
除了直接报告,您还可以引发异常并报告在catch处理程序中:
Instead of reporting directly, you may also throw an exception and report from within the catch handler:
try
{
cin >> age;
if (std::cin.fail())
throw 1;
if (age < 0 || age > 122)
throw 2;
}
catch (int err)
{
// report here according to err
}
有关C ++异常的一般概述,请参见异常-C ++教程 [ ios :: exceptions-C ++参考a> [ ^ ]).
For a general overview of C++ exceptions see Exceptions - C++ Tutorials[^].
You may also enable iostream
exceptions setting the exception mask (see ios::exceptions - C++ Reference[^]).
这篇关于如果有人输入文本而不是数字,C ++如何捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!