本文介绍了c ++,如何验证是数据输入是正确的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞!我是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 removecin.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 (用于被忽略的最大数量< limits> )中定义的字符。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 ++,如何验证是数据输入是正确的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-24 04:45