c++,如何验证输入的数据是正确的数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12721911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:33:34  来源:igfitidea点击:

c++, how to verify is the data input is of the correct datatype

c++cin

提问by Brook Julias

Possible Duplicate:
how do I validate user input as a double in C++?

可能的重复:
如何在 C++ 中将用户输入验证为双精度值?

I am new to C++, and I have a function in which I am wanting the user to input a doublevalue. 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:

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

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

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

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

回答by Zeta

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

如果ostream& operator>>(ostream& , T&)格式化数据(如整数、双精度、浮点数、...)的提取失败,则为stream.fail()真,因此!stream也将评估为真。

So you can use

所以你可以使用

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

or simply

或者干脆

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

It is important to ignorethe 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

ignore对行的其余部分很重要,因为operator>>不会再从流中提取任何数据,因为它的格式错误。所以如果你删除

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

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

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

See also:

也可以看看:

回答by Jesse Good

You need to read the entire line using std::getlineand std::string. That is the way to fully verify that the entire line is of the correct data type:

您需要使用std::getline和阅读整行std::string。这是完全验证整行是否为正确数据类型的方法:

std::string line;
while(std::getline(std::cin, line))
{
    std::stringstream ss(line);
    if ((ss >> radius) && ss.eof())
    {
       // Okay break out of loop
       break;
    }
    else
    {
       // Error!
       std::cout << "Invalid input" << std::endl;
    }
}

回答by Vikas

This example is self explanatory, however with this approach you can't distinguish between intand doubledata types.

这个例子是不言自明的,但是使用这种方法您无法区分intdouble数据类型。

int main()
{
  double number = 0;

  if (!(std::cin >> number))
  {
    std::cout << "That's not a number; ";
  }
  else
  {
    std::cout << "That's  a number; ";
  }
}