[英]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.