[英]Converting Xaml textbox to double, but how to validate that the user input is double not a string in c++ for the windows 8 app
[英]how do I validate user input as a double in C++?
如何检查输入是否真的是双精度?
double x;
while (1) {
cout << '>';
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
}
}
//do other stuff...
上面的代码无限输出Invalid Input!
语句,因此它不会提示再次输入。 我想提示输入,检查它是否合法...如果它是双精度型,请继续...如果它不是双精度型,请再次提示。
有任何想法吗?
尝试这个:
while (1) {
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
这基本上清除了错误状态,然后读取并丢弃了在上一行输入的所有内容。
如果存在解析错误,则会在使用提取运算符后设置failbit
,其中有几个简单的测试功能good
,可以检查fail
。 它们彼此完全相反,因为它们对eofbit
处理方式不同,但是在此示例中这不是问题。
然后,您必须先清除failbit
然后再重试。
正如casablanca所说,您还必须丢弃仍保留在输入缓冲区中的非数字数据。
所以:
double x;
while (1) {
cout << '>';
cin >> x;
if (cin.good())
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
//do other stuff...
#include <iostream>
#include <string>
bool askForDouble(char const *question, double &ret)
{
using namespace std;
while(true)
{
cout << question << flush;
cin >> ret;
if(cin.good())
{
return true;
}
if(cin.eof())
{
return false;
}
// (cin.fail() || cin.bad()) is true here
cin.clear(); // clear state flags
string dummy;
cin >> dummy; // discard a word
}
}
int main()
{
double x;
if(askForDouble("Give me a floating point number! ",x))
{
std::cout << "The double of it is: " << (x*2) << std::endl;
} else
{
std::cerr << "END OF INPUT" << std::endl;
}
return 0;
}
一种方法是检查浮点数是否相等。
double x;
while (1) {
cout << '>';
cin >> x;
if (x != int(x)) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
}
}
bool is_double(double val)
{
bool answer;
double chk;
int double_equl = 0;
double strdouble = 0.0;
strdouble = val;
double_equl = (int)val;
chk = double_equl / strdouble;
if (chk == 1.00)
{
answer = false; // val is integer
return answer;
} else {
answer = true; // val is double
return answer;
}
}
我会用:
double x;
while (!(std::cin >> x)) {
std::cin.clear();
std::cin.ignore(2147483647, '\n');
std::cout << "Error.\n";
}
要么
double x;
while ((std::cout << "> ") && !(std::cin >> x)) {
std::cin.clear();
std::cin.ignore(2147483647, '\n');
std::cout << "Error.\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.