簡體   English   中英

在Visual C ++中進行雙重測試

[英]testing for double in visual c++

我正在用Visual C ++設計GUI,並且有一個文本框,用戶可以在其中輸入值,以便可以執行計算。 如何驗證輸入以確保可以將其轉換為雙精度值?

在任何具有std::string字段並希望檢查它是否包含double C ++環境中,您都可以簡單地執行以下操作:

#include <sstream>

std::istringstream iss(string_value);
double double_value;
char trailing_junk;
if (iss >> double_value && !(iss >> trailing_junk))
{
    // can use the double...
}

如圖所示,這將拒絕"1.234q""-13 what?" 但是接受周圍的空白,例如" 3.9E2 " 如果要拒絕空格,請嘗試#include <iomanip>然后if (iss >> std::noskipws >> double_value && iss.peek() == EOF) ...

您也可以使用舊式C API進行此操作:

double double_value;
if (sscanf(string_value.c_str(), "%lf%*c", &double_value) == 1)

您不能將字符串“ 轉換 ”為雙精度,只能進行轉換 strtod函數將返回一個指針,該指針指向轉換停止的字符串中的字符,因此您可以決定要進一步做什么。 因此,您可以使用此功能進行轉換和檢查。

我建議使用Boost的lexical_cast ,如果轉換失敗,它將拋出異常。

如前所述,strtod(3)是答案。

bool is_double(const char* str) {
    char *end = 0;
    strtod(str, &end);
    // Is the end point of the double the end of string?
    return end == str + strlen(str);
}

為了解決@Ian Goldby的問題,如果擔心字符串末尾的空白,則:

bool is_double(const char* str) {
    char *end = 0;
    strtod(str, &end);
    // Is the end point of the double plus white space the end of string?
    return end + strspn(end, " \t\n\r") == str + strlen(str);
}

由於這似乎是C ++ CLI的相關問題,並且文本框中的字符串可能是.NET字符串,因此您可能需要檢查靜態Double :: Parse方法。 有關更多便攜式解決方案,請參見其他答案...

只需將其轉換為雙精度值即可。 如果成功,則輸入有效。

確實,您不應該編寫自己的規則來確定有效內容。 您將永遠不會獲得與庫函數完全相同的規則來進行實際的轉換。

我最喜歡的方法是使用sscanf(),並檢查返回值以確保准確轉換了一個字段。 要獲得額外的榮譽,請使用%n參數檢查是否沒有剩余非空白字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM