C++中stringstream的使用方法和样例

转载自:https://blog.csdn.net/sophia1224/article/details/53054698

之前在leetcode中进行string和int的转化时使用过istringstream,现在大致总结一下用法和测试用例。  

  介绍:C++引入了ostringstream、istringstream、stringstream这三个类,要使用他们创建对象就必须包含sstream.h头文件。

istringstream类用于执行C++风格的串流的输入操作。

ostringstream类用于执行C风格的串流的输出操作。 

stringstream类同时可以支持C风格的串流的输入输出操作。

下图详细描述了几种类之间的继承关系:


istringstream是由一个string对象构造而来,从一个string对象读取字符。 
ostringstream同样是有一个string对象构造而来,向一个string对象插入字符。
stringstream则是用于C++风格的字符串的输入输出的。 

代码测试:
[cpp]  view plain  copy
  1. #include<iostream>  
  2. #include <sstream>   
  3. using namespace std;<pre name="code" class="cpp">int main(){  
  4.     string test = "-123 9.87 welcome to, 989, test!";  
  5.     istringstream iss;//istringstream提供读 string 的功能  
  6.     iss.str(test);//将 string 类型的 test 复制给 iss,返回 void   
  7.     string s;  
  8.     cout << "按照空格读取字符串:" << endl;  
  9.     while (iss >> s){  
  10.         cout << s << endl;//按空格读取string  
  11.     }  
  12.     cout << "*********************" << endl;  
  13.   
  14.     istringstream strm(test);   
  15.     //创建存储 test 的副本的 stringstream 对象  
  16.     int i;  
  17.     float f;  
  18.     char c;  
  19.     char buff[1024];  
  20.   
  21.     strm >> i;  
  22.     cout <<"读取int类型:"<< i << endl;  
  23.     strm >> f;  
  24.     cout <<"读取float类型:"<<f << endl;  
  25.     strm >> c;  
  26.     cout <<"读取char类型:"<< c << endl;  
  27.     strm >> buff;  
  28.     cout <<"读取buffer类型:"<< buff << endl;  
  29.     strm.ignore(100, ',');  
  30.     int j;  
  31.     strm >> j;  
  32.     cout <<"忽略‘,’读取int类型:"<< j << endl;  
  33.   
  34.     system("pause");  
  35.     return 0;  
  36. }  
 
  输出: 
 
总结:
1)在istringstream类中,构造字符串流时,空格会成为字符串参数的内部分界;
2)istringstream类可以用作string与各种类型的转换途径
3)ignore函数参数:需要读取字符串的最大长度,需要忽略的字符
代码测试:
[cpp]  view plain  copy
  1. int main(){  
  2.     ostringstream out;  
  3.     out.put('t');//插入字符  
  4.     out.put('e');  
  5.     out << "st";  
  6.     string res = out.str();//提取字符串;  
  7.     cout << res << endl;  
  8.     system("pause");  
  9.     return 0;  
  10. }  
输出:test字符串;
注:如果一开始初始化ostringstream,例如ostringstream out("test"),那么之后put或者<<时的字符串会覆盖原来的字符,超过的部分在原始基础上增加。

stringstream同理,三类都可以用来字符串和不同类型转换。

猜你喜欢

转载自blog.csdn.net/qianpeng4/article/details/80537608