如何检测 atof 或 _wtof 是否无法将字符串转换为双精度?但不是通过尝试检查结果是否与 0.0 不同,因为我的输入可以是 0.0。谢谢!
8412 次
2 回答
15
不要使用atof. 相反,使用strtod, from <cstdlib>,并检查errnofrom <cerrno>:
// 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, from <string>,但我相信如果转换失败会引发异常,这在处理外部数据时可能不是理想的故障模式。
于 2012-09-11T11:53:12.043 回答
1
使用atof,你不能。但由于这是 C++,我建议你使用 astd::stringstream并operator !在应用operator >>到 a后检查它double。
于 2012-09-11T11:53:30.967 回答