string和各内置类型的互换方法(stringstream的一种用法)

/*和c的转换函数比起来用法更为隐蔽,对初学者来说不够直观。*/

#include "iostream"
#include "sstream"
#include "string"
#include "cstdlib"
using namespace std;
int main(void)
{
/*以下是内置类型向string转换的解决方案*/
 int ival;
 char cval;
 ostringstream out_string;
 string str;
 
 ival = 100;
 cval = 'w';
 out_string << ival << " " << cval;
 str = out_string.str();
 cout << str << endl;

/*以下是string向内置类型转换的解决方案*/  
 int itmpe;
 char ctmpe;
 str = "100k";
 istringstream in_string( str );
 in_string >> itmpe >> ctmpe;
 cout << itmpe << " " << ctmpe << endl;
 system( "PAUSE" );
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章