2012-09-11 37 views
7

如何檢測atof或_wtof failes是否將字符串轉換爲double?但不是試圖檢查結果是不同的形式0.0,因爲我的輸入可以是0.0。謝謝!如何檢測atof或_wtof失敗?

+2

您剛剛發現使用atoX函數的原因很糟糕。 – PlasmaHH

回答

11

請勿使用atof。相反,使用strtod,從<cstdlib>,也從<cerrno>檢查errno

// assume: "char * mystr" is a null-terminated string 

char * e; 
errno = 0; 
double x = std::strtod(mystring, &e); 

if (*e != '\0' || // error, we didn't consume the entire string 
    errno != 0) // error, overflow or underflow 
{ 
    // fail 
} 

指針e點之一過去的最後一個字符消耗。您也可以檢查e == mystr以查看是否有個字符被佔用。

還有std::wcstodwchar_t-strings,從<cwstring>

在C++ 11還必須std::to_string/std::to_wstring,從<string>,但是相信如果轉換失敗,與外部數據處理時,其可能不期望的故障模式拋出異常。

+0

@TerranceCohen:不。(但是你可能仍然想要檢查'errno'來捕獲和下溢。) –

1

使用atof,你不能。但是由於這是C++,我建議你使用std::stringstream,並在operator >>應用到double之後用operator !檢查它。