c ++,如何验证是数据输入是正确的数据类型 [英] c++, how to verify is the data input is of the correct datatype

查看:368
本文介绍了c ++,如何验证是数据输入是正确的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在C ++中将用户输入验证为双重?

我是C ++的新手,我有一个函数,我希望用户输入 double 。我将如何确保值输入是正确的数据类型?此外,如何处理错误?目前这是我所有的:

I am new to C++, and I have a function in which I am wanting the user to input a double value. How would I go about insuring that the value input was of the correct datatype? Also, how would an error be handled? At the moment this is all I have:

if(cin >> radius){}else{}

我使用`try {} catch(){},但我不认为这将是正确的解决方案这个问题。任何帮助将不胜感激。

I using `try{}catch(){}, but I don't think that would the right solution for this issue. Any help would be appreciated.

推荐答案

如果 ostream& (如整数,双精度,浮点数,...), stream.fail()<>; / code>将会是真的,因此!stream 也会计算为true。

If ostream& operator>>(ostream& , T&) fails the extraction of formatted data (such as integer, double, float, ...), stream.fail() will be true and thus !stream will evaluate to true too.

使用

cin >> radius;
if(!cin){
    cout << "Bad value!";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin >> radius;
}

或只是

while(!(cin >> radius)){
    cout << "Bad value!";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

忽略其余的行,因为 operator>> 将不会从流中提取任何数据,因为它是一个错误的格式。因此,如果您删除

It is important to ignore the rest of the line, since operator>> won't extract any data from the stream anymore as it is in a wrong format. So if you remove

cin.ignore(numeric_limits<streamsize>::max(), '\n');

您的循环永远不会结束,因为输入未从标准输入中清除。

your loop will never end, as the input isn't cleared from the standard input.

另请参阅:

  • std::basic_istream::ignore (cin.ignore)
  • std::basic_istream::fail (cin.fail())
  • std::numeric_limits (used for the maximum number of ignored characters, defined in <limits>).

这篇关于c ++,如何验证是数据输入是正确的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆