istringstream、ostringstream、stringstream 类介绍 和 stringstream类 clear函数的真正用途

来源: http://blog.csdn.net/TQH_Candy/article/details/52494570

0、C++的输入输出分为三种:

(1)基于控制台的I/O

(2)基于文件的I/O

(3)基于字符串的I/O

1、头文件

  1. #include <sstream>

2、作用

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

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

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

3、具体分析

istringstream类

描述:从流中提取数据,支持 >> 操作

这里字符串可以包括多个单词,单词之间使用空格分开

  1. istringstream的构造函数原形:
  2. istringstream::istringstream(string str);

初始化:使用字符串进行初始化

  1. istringstream istr("1 56.7");
  2. istr.str("1 56.7");//把字符串"1 56.7"存入字符串流中

使用:我们可以使用分解点获取不同的数据,完成 字符串 到 其他类型 的转换

常用成员函数:

  1. str():使istringstream对象返回一个string字符串

举例:把字符串类型的数据转换为其他类型

  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. istringstream istr("1 56.7");
  7. cout<<istr.str()<<endl;//直接输出字符串的数据 "1 56.7"
  8. string str = istr.str();//函数str()返回一个字符串
  9. cout<<str<<endl;
  10. int n;
  11. double d;
  12. //以空格为界,把istringstream中数据取出,应进行类型转换
  13. istr>>n;//第一个数为整型数据,输出1
  14. istr>>d;//第二个数位浮点数,输出56.7
  15. //假设换下存储类型
  16. istr>>d;//istringstream第一个数要自动变成浮点型,输出仍为1
  17. istr>>n;//istringstream第二个数要自动变成整型,有数字的阶段,输出为56
  18. //测试输出
  19. cout<<d<<endl;
  20. cout<<n<<endl;
  21. system("pause");
  22. return 1;
  23. }

举例2:把一行字符串放入流中,单词以空格隔开。之后把一个个单词从流中依次读取到字符串

  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. istringstream istr;
  7. string line,str;
  8. while (getline(cin,line))//从终端接收一行字符串,并放入字符串line中
  9. {
  10. istr.str(line);//把line中的字符串存入字符串流中
  11. while(istr >> str)//每次读取一个单词(以空格为界),存入str中
  12. {
  13. cout<<str<<endl;
  14. }
  15. }
  16. system("pause");
  17. return 1;
  18. }

输入:123 34 45

输出:

123  换行 34 换行 45

ostringstream类

描述:把其他类型的数据写入流(往流中写入数据),支持<<操作

  1. ostringstream的构造函数原形:
  2. ostringstream::ostringstream(string str);

初始化:使用字符串进行初始化

  1. ostringstream ostr("1234");
  2. ostr.str("1234");//把字符串"1234"存入字符串流中

举例:

  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4. int main()
  5. {
  6. //初始化输出字符串流ostr
  7. ostringstream ostr("1234");
  8. cout<<ostr.str()<<endl;//输出1234
  9. ostr.put('5');//字符4顶替了1的位置
  10. cout<<ostr.str()<<endl;//输出5234
  11. ostr<<"67";//字符串67替代了23的位置,输出5674
  12. string str = ostr.str();
  13. cout<<str<<endl;
  14. system("pause");
  15. return 1;
  16. }

stringstream类

描述:是对istringstream和ostringstream类的综合,支持<<, >>操作符,可以进行字符串到其它类型的快速转换

  1. stringstream的构造函数原形如下:
  2. stringstream::stringstream(string str);

初始化:使用字符串进行初始化

  1. stringstream str("1234");
  2. str.str("1234");//把字符串"1234"存入字符串流中

作用:

1、stringstream通常是用来做数据转换的

2、将文件的所有数据一次性读入内存

举例1:基本数据类型变字符串

  1. /*基本数据类型变字符串*/
  2. #include <fstream>
  3. #include <iostream>
  4. #include <sstream>
  5. using namespace std;
  6. int main()
  7. {
  8. /*整型变字符串*/
  9. int n = 10;
  10. string str;
  11. stringstream stream;
  12. stream << n;
  13. stream >> str;
  14. cout<<str<<endl;
  15. stream.clear();//多次使用stringstream,要先清空下,不能使用stream.str("");否则下面输出10
  16. /*char* 变 string*/
  17. char cStr[10] = "china";
  18. stream << cStr;
  19. stream >> str;
  20. cout<<str<<endl;
  21. system("pause");
  22. return 1;
  23. }

举例2:字符串变基本数据类型

  1. /*字符串变基本数据类型*/
  2. #include <fstream>
  3. #include <iostream>
  4. #include <sstream>
  5. using namespace std;
  6. int main()
  7. {
  8. /*字符串 变 double*/
  9. double n;
  10. string str = "12.5";
  11. stringstream stream;
  12. stream << str;
  13. stream >> n;
  14. cout<<n<<endl;
  15. stream.clear();//多次使用stringstream,要先清空下,不能使用stream.str("");
  16. /*string 变 char* */
  17. string str1 = "china";
  18. char cStr[10];
  19. stream << str1;
  20. stream >> cStr;
  21. cout<<cStr<<endl;//输出china
  22. system("pause");
  23. return 1;
  24. }
  1. 注意:
  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4. int main(int argc,char *argv[])
  5. {
  6. std::stringstream stream;
  7. string str;
  8. while(1)
  9. {
  10. //clear(),这个名字让很多人想当然地认为它会清除流的内容。
  11. //实际上,它并不清空任何内容,它只是重置了流的状态标志而已!
  12. stream.clear();
  13. // 去掉下面这行注释,清空stringstream的缓冲,每次循环内存消耗将不再增加!
  14. //stream.str("");
  15. stream<<"sdfsdfdsfsadfsdafsdfsdgsdgsdgsadgdsgsdagasdgsdagsadgsdgsgdsagsadgs";
  16. stream>>str;
  17. //测试输出每次循环,你的内存消耗增加了多少!
  18. cout<<"Size of stream = "<<stream.str().length()<<endl;
  19. system("PAUSE");
  20. }
  21. system("PAUSE");
  22. return EXIT_SUCCESS;
  23. }

由于stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。

另外不要企图用 stream.str().resize(0),或 stream.str().clear() 来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果,内存的消耗还在缓慢的增长!,至于stream.flush(),则根本就起不到任何作用。

//=============================================

究竟什么情况下需要用到clear

先来看一个stack overflow上的问题(http://stackoverflow.com/questions/35080342/using-two-string-streams-but-not-getting-same-result

我将其简化为以下代码:

  1. int main() {
  2. string line = "1 2 3 4 5";
  3. stringstream s1(line);
  4. string temp;
  5. int toAdd;
  6. stringstream s2;
  7. while (s1 >> temp) {
  8. cout << "temp:" << temp << endl;
  9. s2 << temp;
  10. cout << "s2.str: " << s2.str() << endl;
  11. s2 >> toAdd;
  12. cout << "toAdd:" << toAdd << endl;
  13. s2.str("");
  14. }
  15. return 0;
  16. }

这个代码的原意是要把line中的字符串形式的1 2 3 4 5一个一个地转成int并输出,所以我们期望的toAdd的输出应该是1 2 3 4 5,但结果却是 1 1 1 1 1, 如下图

 

可以从s2.str:这句输出中看到, 只有第一次是正常地把temp输入进s2,后面的都失败了。

原因在于, s2在第一次调用完operator<<和operator>>后,来到了end-of-file的位置,此时stringstream会为其设置一个eofbit的标记位,标记其为已经到达eof。查文档得知, 当stringstream设置了eofbit,任何读取eof的操作都会失败,同时,会设置failbit的标记位,标记为失败状态。所以后面的操作都失败了,toAdd的值一直都是1。

Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.

clear函数:

原型: void clear (iostate state = goodbit);

标志位一共有4种, goodbit, eofbit, failbit, badbit

clear可以清除掉所有的error state

  1. int main() {
  2. string line = "1 2 3 4 5";
  3. stringstream s1(line);
  4. string temp;
  5. int toAdd;
  6. stringstream s2;
  7. while (s1 >> temp) {
  8. cout << "temp:" << temp << endl;
  9. s2 << temp;
  10. cout << "s2.str: " << s2.str() << endl;
  11. s2 >> toAdd;
  12. cout << "toAdd:" << toAdd << endl;
  13. s2.str("");
  14. if (s2.eof()) {
  15. s2.clear();
  16. cout << "s2.eof true" << endl;
  17. }
  18. }
  19. return 0;
  20. }

使用clear后, s2就可以正常地工作了,结果如下:  

参考网站:http://www.cplusplus.com/reference/sstream/stringstream/

       http://www.cplusplus.com/reference/ios/ios/clear/

istringstream、ostringstream、stringstream 类介绍 和 stringstream类 clear函数的真正用途的更多相关文章

  1. JavaACOFramework的各个类介绍(part1 : Ant类)

    public abstract class Ant extends Observable implements Runnable { public static int ANT_ID = 1; // ...

  2. JavaACOFramework的各个类介绍(part2 : Ant4AS类)

    package aco.ant; import java.util.ArrayList; import util.RouletteWheel;//引入轮盘类 import aco.ACO;//引入蚁群 ...

  3. SimpleDateFormat类介绍和 DateFormat类的format方法和parse方法

    使用 SimpleDateFormat格式化日期 SimpleDateFormat 是一个以语言环境敏感的方式来格式化和分析日期的类.SimpleDateFormat 允许你选择任何用户自定义日期时间 ...

  4. JavaACOFramework的各个类介绍(part3 : Ant4ACS类)

    package aco.ant; import java.util.ArrayList; import sys.Settings; import util.PseudoRandom; import a ...

  5. istringstream、ostringstream、stringstream 类介绍 .

    istringstream.ostringstream.stringstream 类介绍 . 转自:http://www.cnblogs.com/gamesky/archive/2013/01/09/ ...

  6. stringstream istringstream ostringstream 三者的区别

    stringstream istringstream ostringstream 三者的区别 说明 ostringstream : 用于执行C风格字符串的输出操作. istringstream : 用 ...

  7. CYQ.Data.Orm.DBFast 新增类介绍(含类的源码及新版本配置工具源码)

    前言: 以下功能在国庆期就完成并提前发布了,但到今天才有时间写文介绍,主要是国庆后还是选择就职了,悲催的是上班的地方全公司都能上网,唯独开发部竟不让上网,是个局域网. 也不是全不能上,房间里有三台能上 ...

  8. Bullet核心类介绍(Bullet 2.82 HelloWorld程序及其详解,附程序代码)

    实验平台:win7,VS2010 先上结果截图: 文章最后附有生成该图的程序. 1. 刚体模拟原理 Bullet作为一个物理引擎,其任务就是刚体模拟(还有可变形体模拟).刚体模拟,就是要计算预测物体的 ...

  9. MediaRecorder类介绍

    audiocallbackvideojavadescriptorencoding 目录(?)[+] 找到个MediaRecorder类介绍和大家分享一下. Mediarecorder类在官网的介绍和在 ...

随机推荐

  1. CM记录-Hbase启用安全认证控制

    1.cm-cluster2-HBase-2-HBase 安全授权(hbase.security.authorization)-simple改为true 2.添加配置 1)超级用户-加入root.hba ...

  2. 运用Zabbix实现内网服务器状态及局域网状况监控(3) —— Zabbix服务端安装

    1. Zabbix服务端安装,基于LNMP PHP5.5+Nginx1.9安装配置:http://www.cnblogs.com/vurtne-lu/p/7707536.html MySQL5.5编译 ...

  3. python 面试题--你能做出多少?

    python3中__get__,getattr,__getattribute__的区别 什么是 GIL 详细博客 GIL = Global Intercept Lock 全局解释器锁,任意时刻在解释器 ...

  4. python 代码模板

    命令[python3 -m pydoc -p 1234]   通过http://localhost:1234来访问查看文档 # -*- coding: utf-8 -*-""&qu ...

  5. 四、移植 JZ2440 开发板

    4.1 移植第一步 前面已经分析过了 .config 的过程,可以知道移植需要用到的文件: .config 文件 arch/arm/cpu 下的文件 board 目录  .config 文件是根据后面 ...

  6. IT阅读——关于“业务”

    本文转自http://www.cnblogs.com/beijiguangyong/archive/2012/11/12/2767054.html 开发当中常常听说“业务”这个词,什么“业务为王”之类 ...

  7. java操作Hbase

    public class Test { public Connection connection; // 用HBaseconfiguration初始化配置信息是会自动加载当前应用的classpath下 ...

  8. android 简单文件操作

    1.布局 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:too ...

  9. elasticsearch 单机多实例

    elasticsearch 配置单机器多实例 host: - - path data: /opt/elasticsearch/data/node1 /opt/elasticsearch/data/no ...

  10. HKE和他的小朋友(矩乘快速幂)

    题面: 题目背景: HKE带着\(n\)个小朋友做游戏 题目描述: 现在有n个座位编号为\(1\)至\(n\),这些小朋友也编号\(1\)至\(n\).一开始所有小朋友都坐在相应的座位上.HKE的游戏 ...