如何檢測atof或_wtof failes是否將字符串轉換爲double?但不是試圖檢查結果是不同的形式0.0,因爲我的輸入可以是0.0。謝謝!如何檢測atof或_wtof失敗?
7
A
回答
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::wcstod
與wchar_t
-strings,從<cwstring>
。
在C++ 11還必須std::to_string
/std::to_wstring
,從<string>
,但是相信如果轉換失敗,與外部數據處理時,其可能不期望的故障模式拋出異常。
+0
@TerranceCohen:不。(但是你可能仍然想要檢查'errno'來捕獲和下溢。) –
1
使用atof
,你不能。但是由於這是C++,我建議你使用std::stringstream
,並在operator >>
應用到double
之後用operator !
檢查它。
相關問題
- 1. C++ ATOF/_wtof,舍入誤差
- 2. ImportPSModule失敗檢測
- 3. 檢測chrome.extension.sendRequest失敗
- 4. 檢測strtol失敗
- 5. 如何檢測所有http GET失敗?
- 6. 如何檢測失敗的Windows登錄
- 7. 如何檢測window.location是否失敗?
- 8. 如何檢測rpm後腳本失敗
- 9. 如何檢測docker-py client.build()失敗時
- 10. 如何檢測DownloadString是否失敗?
- 11. 石英如何檢測節點失敗
- 12. 如何檢測幾個AJAX請求已完成或失敗?
- 13. 如何在Silverlight中檢測SetBinding成功或失敗?
- 14. 套接字失敗檢測
- 15. 碰撞檢測失敗Box2d
- 16. 代理對檢測失敗
- 17. Heroku Ruby Buildpack檢測失敗
- 18. 檢測UIScreenEdgeGestureRecognizer並失敗UIPanGestureRecognizer
- 19. Cassandra失敗檢測器
- 20. 檢測上傳失敗
- 21. 檢測mailto失敗時
- 22. pygame失敗檢測鍵盤
- 23. 失敗的recaptcha檢測
- 24. 檢測/修復NSConnection失敗
- 25. 如何檢測Selenium html測試中的測試失敗?
- 26. 在@After方法中檢測Junit測試失敗或錯誤
- 27. 我如何檢測CodedUI測試失敗編程?
- 28. 如何使用rake檢測失敗的單元測試
- 29. 替代atof()函數來區分輸入0與失敗
- 30. 安裝MSI時,如何以編程方式檢測成功或失敗?
您剛剛發現使用atoX函數的原因很糟糕。 – PlasmaHH