C++ std::string 與數字型別互轉

STL 所提供的 sstream library

C 的 atoi 跟 itoa 等價的字串數字互轉,可以用 C++ 的 ostream::operator>>istream::operator<< 所提供的 FormattedInputFunctionFormattedOutputFunction 來取代。因為 Stream 本身就是一個大字串了,STL 為了要將標準 Stream Unformated Data,傳達到 C++ 的 Typed System,自己就寫了一大份數值轉換 Functions 放在 Iostream 系統裡。

string to double
string str_pi = "3.14";
double pi = 0.0;
sringstream(pi) >> pi;
  • stringstream(pi) > pi 就像是 cin >> pi 一樣,會把你打入的字串,轉換成數字。
double to string
double pi = 3.14;
string str_pi = (stringstream() << pi).str();
  • stringstream() 會產生一個暫時物件 t
  • t << pi 運算會回傳吃進 pi:3.14stringstream:t
  • t.str() 會回傳內部 string 的 buffer

不只有 typesafe,還有豐富的 type 支援

to string

basic_ostream& operator<<( short value );
basic_ostream& operator<<( unsigned short value );
basic_ostream& operator<<( int value );
basic_ostream& operator<<( unsigned int value );
basic_ostream& operator<<( long value );
basic_ostream& operator<<( unsigned long value );
basic_ostream& operator<<( long long value );
basic_ostream& operator<<( unsigned long long value );
basic_ostream& operator<<( float value );
basic_ostream& operator<<( double value );
basic_ostream& operator<<( long double value );
basic_ostream& operator<<( bool value );
basic_ostream& operator<<( const void* value );

to numeric type

basic_istream& operator>>( short& value );
basic_istream& operator>>( unsigned short& value );
basic_istream& operator>>( int& value );
basic_istream& operator>>( unsigned int& value );
basic_istream& operator>>( long& value );
basic_istream& operator>>( unsigned long& value );
basic_istream& operator>>( long long& value );
basic_istream& operator>>( unsigned long long& value );
basic_istream& operator>>( float& value );
basic_istream& operator>>( double& value );
basic_istream& operator>>( long double& value );
basic_istream& operator>>( bool& value );
basic_istream& operator>>( void*& value );

麻煩的地方

  • #include <sstream>
  • 數字需要 lvalue
  • 若要判斷轉換是否成功,不能用 temporary stringstream() ,要用 lvaluestringstream,因為轉換狀態是放在 stringstream 本體,使用 temporary 會在那行結束時即消失,無法得知訊息。
comments powered by Disqus