2013-09-27 14 views
2

我需要將寬字符串轉換爲double數字。據推測,該字符串是一個數字,沒有別的(也許有些空格)。如果字符串中包含其他內容,則應指出錯誤。所以我不能使用stringstream - 如果字符串包含其他內容,它將提取一個數字而不指出錯誤。通過錯誤檢查將wstring轉換爲double的方法

wcstod看起來是一個完美的解決方案,但它在Android上運行錯誤(GCC 4.8,NDK r9)。我可以嘗試什麼其他選項?

+1

使用['std :: stod'](http://en.cppreference.com/w/cpp/string/basic_string/stof)它會在輸入錯誤時引發異常。 – deepmax

+0

「如果字符串包含其他內容,它將提取一個數字而不指示錯誤。」咦?如果提取失敗,應該設置'failbit'。 (如果你啓用'stringstream'的異常,你也會得到一個異常。) – dyp

+0

@MM .:這是'strtod'的包裝,我相信,而且我的輸入是寬字符串。 –

回答

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'; 
} 

打印

$ ./a.out 
123 
0 

(我只是在錯誤返回0這種情況對我來說很簡單,你可能想要throw什麼的)。

當然還有其他的選擇。我只是覺得你的評估是不公平的stringstream。順便說一句,這是少數情況下,你其實想檢查eof()

編輯:好的,我添加了w s和L s以使用wchar_t s。

編輯:這是第二個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; 
} 
+0

'wistringstream'和'wstring'。除此之外,+1。 – dyp

+0

'if(!(iss >> parsed))'check'是什麼意思? 'operator >>''返回'istream&',而不是bool。 istream是否可轉換爲bool? –

+0

@VioletGiraffe粗略地說,是的,完全是這個目的。在C++ 03中,['std :: basic_ios'](http://en.cppreference.com/w/cpp/io/basic_ios)有一個['operator operator *'](http://en.cppreference .com/w/cpp/io/basic_ios/operator_bool),如果fail()返回true,則返回空指針。截至2011年,它有一個'顯式運算符bool',它的行爲像這樣(http://chris-sharpe.blogspot.co.uk/2013/07/contextually-converted-to-bool.html)。基本上,它讀取,然後檢查讀取沒有失敗。 – BoBTFish

相關問題