を使用してから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
。ところで、これは実際にチェックしたい数少ないケースの 1 つですeof()
。
編集:わかりました、s を使用するためにw
s とs を追加しました。L
wchar_t
編集: これは、2 番目の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;
}