stringstream用法

来源:互联网 发布:数据分析师主要做什么 编辑:程序博客网 时间:2024/05/22 11:41

stringstream用法

分为istream和ostringstream.

1     std::string name("zeta");2     int age = 27;3 4     ostringstream os;5     os << "name:"<<name<<""<<"age:"<<age<<endl;6     cout<<os.str()<<endl;

输出:name:zeta age:27


 

复制代码
 1     std::string name("zeta"); 2     int age = 27; 3  4     ostringstream os; 5     os << "name:"<<name<<""<<"age:"<<age<<"\n"; 6  7     istringstream is(os.str()); 8     std::string tmp; 9     int age1;10 11     // name:zeta12     is >> tmp;13     cout<<tmp<<endl;14 15     // age:2716     is >> tmp;17     cout<<tmp<<endl;
复制代码

注释为输出结果,注意从stringstream中解析对象的时候,是以空格和回车键为分隔符的。

 

复制代码
1     std::string name("12345");2     int age = 27;3     stringstream os;4     os << name;5     os >> age;6     // age = 123457     cout<<age<<endl;
复制代码

 

复制代码
1     std::string name("12345");2     int age = 27;3     stringstream os;4     os << age;5     os >> name;6     // name:277     cout<<name<<endl;
复制代码

可以作为将数字和字符串相互转化的工具。



 

输入输出的头文件 <iostream> 
string流的头文件 <sstream> 
文件流的头文件   <fstream>

 

stringstream的用法

 

1.利用输入输出做数据转换

 

stringstream ss_stream;ss_stream << i;   // 将int输入流中ss_stream >> str; // 将ss_stream中的数值输出到str中//注意:如果做多次数据转换;必须调用clear()来设置转换模式ss_stream << "456"; ss_stream >> i;   // 首先将字符串转换为intss_stream.clear();ss_stream << true;ss_stream >> i;   // 然后将bool型转换为int;假如之前没有做clear,那么i会出错//运行clear的结果 i = 456 i = 1 //没有运行clear的结果 i = 456 i = 8800090900 

 

 

 

 

 

2.支持char*的输入和输出

 

char sz_buf[20];ss_stream << 8888;ss_stream >> sz_buf; // 直接将数输出到sz_buf字符数组中

 

0 0
原创粉丝点击