我需要将宽字符串转换为 double 字。据推测,该字符串包含一个数字,没有其他内容(可能包含一些空格)。如果字符串包含其他内容,则应指示错误。所以我不能使用 stringstream - 如果字符串包含其他内容,它会提取一个数字而不指示错误。
wcstod
似乎是一个完美的解决方案,但它在 Android 上运行错误(GCC 4.8、NDK r9)。我还可以尝试哪些其他选择?
最佳答案
您可以使用stringstream
,然后使用std:ws
检查流上的任何剩余字符是否仅为空格:
double parseNum (const std::wstring& s)
{
std::wistringstream iss(s);
double parsed;
if ( !(iss >> parsed) )
{
// couldn't parse a double
return 0;
}
if ( !(iss >> std::ws && iss.eof()) )
{
// something after the double that wasn't whitespace
return 0;
}
return parsed;
}
int main()
{
std::cout << parseNum(L" 123 \n ") << '\n';
std::cout << parseNum(L" 123 asd \n ") << '\n';
}
打印
$ ./a.out
123
0
(我刚刚在错误情况下返回了 0
,对于我的示例来说是快速而简单的。您可能想要抛出
或其他东西)。
当然还有其他选择。我只是觉得你对 stringstream
的评价不公平。顺便说一句,这是您实际上确实想要检查eof()
的少数情况之一。
编辑:好的,我添加了 w
和 L
来使用 wchar_t
。
编辑:从概念上讲,这是第二个 if
的扩展内容。可能有助于理解为什么它是正确的。
if ( iss >> std::ws )
{ // successfully read some (possibly none) whitespace
if ( iss.eof() )
{ // and hit the end of the stream, so we know there was no garbage
return parsed;
}
else
{ // something after the double that wasn't whitespace
return 0;
}
}
else
{ // something went wrong trying to read whitespace
return 0;
}
关于c++ - 通过错误检查将 wstring 转换为 double 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19051506/