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

Vio*_*ffe 2 c++ string double type-conversion

我需要将一个宽字符串转换为双数字.据推测,字符串保持一个数字而没有别的(可能是一些空格).如果字符串包含其他内容,则应指出错误.所以我不能使用stringstream- 如果字符串包含其他内容,它将提取一个数字而不指示错误.

wcstod似乎是一个完美的解决方案,但它在Android上运行错误(GCC 4.8,NDK r9).我还可以尝试其他什么选择?

BoB*_*ish 5

您可以使用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';
}
Run Code Online (Sandbox Code Playgroud)

版画

$ ./a.out 
123
0
Run Code Online (Sandbox Code Playgroud)

(我刚刚0在错误的情况下返回,作为我的例子的快速和简单的东西.你可能想要throw或某事).

当然还有其他选择.我觉得你的评价是不公平的stringstream.顺便说一句,这是为数不多的情况下,你居然一个想检查eof().

编辑:好的,我添加了ws和Ls来使用wchar_ts.

编辑:这是第二个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;
}
Run Code Online (Sandbox Code Playgroud)