C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
/* <sstream>库定义了三种类: istringstream ostringstream stringstream 分别用来进行字符串流的输入、输出和输入输出操作。 */ #include <string> // std::string #include <iostream> // std::cout #include <sstream> // std::stringstream, std::stringbuf template < typename out_type, typename in_value> out_type convert( const in_value& t) { std::stringstream stream; stream << t; //向流中传值 out_type result; //这里存储转换结果 stream >> result; //向result中写入值 return result; } int main () { std::stringstream ss; //void str (const string& s); ss.str( "Michael Joessy" ); //string str() const; std::string str = ss.str(); std::cout << str << std::endl; //void clear (iostate state = goodbit); ss.clear(); ss.str( "" ); //使用stringstream对象简化类型转换 double d; std::string strSalary; std::string myStr = "12.56" ; d = convert< double >(myStr); strSalary = convert<std::string>( 10000 ); std::cout << strSalary << std::endl; //operator<< std::stringstream strbuf; strbuf << "Good Good Study" ; strbuf << "," ; strbuf << "Day Day Up!" ; std::cout << strbuf.str() << std::endl; std::cin.get(); return 0 ; } |