std::stringstream
を使用する operator>>()
の結果を取得します .
例:
#include <string>
#include <iostream>
#include <sstream>
int main(int, char*[])
{
std::stringstream sstr1("12345");
std::stringstream sstr2("foo");
int i1(0);
int i2(0);
//C++98
bool success1 = sstr1 >> i1;
//C++11 (previous is forbidden in c++11)
success1 = sstr1.good();
//C++98
bool success2 = sstr2 >> i2;
//C++11 (previous is forbidden in c++11)
success2 = sstr2.good();
std::cout << "i1=" << i1 << " success=" << success1 << std::endl;
std::cout << "i2=" << i2 << " success=" << success2 << std::endl;
return 0;
}
版画:
i1=12345 success=1
i2=0 success=0
注、これは基本的に boost::lexical_cast
です ただし、boost::lexical_cast
を除く boost::bad_lexical_cast
をスローします 戻りコードを使用する代わりに失敗時の例外。
参照:http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html
std::stringstream::good については、http://www.cplusplus.com/reference/ios/ios/good/ を参照してください。
例外を回避するには、例外が存在しなかった時代に戻ります。これらの関数は C から引き継がれましたが、今日でも有用です:strtod
と strtol
. ( strtof
もあります ただし、double は自動で float に変換されます)。ゼロの文字値で示されるように、デコードが文字列の最後に到達したかどうかを確認することで、エラーをチェックします。
char * pEnd = NULL;
double d = strtod(str.c_str(), &pEnd);
if (*pEnd) // error was detected