c++ - 通过错误检查将 wstring 转换为 double 的方法

标签 c++ string type-conversion double

我需要将宽字符串转换为 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()的少数情况之一。

编辑:好的,我添加了 wL 来使用 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/

相关文章:

C++ 运行时抢占堆栈溢出

c++ - xcode c++ sqlite3 symbol(s) not found for architecture x86_64

c++ - 如何在 C++ 的 switch 语句中使用枚举值?

javascript - 具有递归函数的程序

python - 找到一个被三个大写字母包围的小写字母

haskell - 为 GADT 定义您自己的 Typeable 实例

c# - 由于某种原因,字节乘以字节是 int。为什么?无法将类型 'int' 隐式转换为 'byte' 。存在显式转换

c++ - 如何改进 Tesseract 结果

javascript - 在此代码中将日期格式化为 dd/MM/yyyy

java - 将 32 位无符号整数(大端)转换为长整数并返回