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

亡梦爱人 提交于 2019-12-17 18:55:18

问题


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

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{}

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


回答1:


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.

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 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.

See also:

  • 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>).



回答2:


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

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;
    }
}



回答3:


This example is self explanatory, however with this approach you can't distinguish between int and double data types.

int main()
{
  double number = 0;

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


来源:https://stackoverflow.com/questions/12721911/c-how-to-verify-is-the-data-input-is-of-the-correct-datatype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!