std IO库, stringstream, 简看1

IO Stream Library : Standard Input Output Stream Library,   这是一个面向对象的库, 用流的方式提供input,output功能

写了一个关于stringstream的小测试程序

 1 #include<string>
 2 #include<iostream>
 3 #include<sstream>
 4 using namespace std;
 5 int main ()
 6 {
 7     stringstream ss;
 8     int i1 = 123;
 9     ss << i1;
10     string str1 = ss.str();
11     // line
12     ss.str("");
13     int i2 = 6589;
14     ss << i2;
15     ss << "thea";
16     string str2 = ss.str();
17 
18     cout << "str1 :" << str1 << endl
19          << "str2 :" << str2 << endl;
20     string str3;
21     int i3 = 0;
22     
23     ss.ignore(3);
24     char ch[3];
25     ss.read(ch, 3);
26     cout.write(ch, 3);
27     cout << endl;
28     ss >> str3;
29     ss >> i3;
30     cout << "str3 :" << str3 << endl;
31     cout << "i3 :" << i3 << endl;
32     return 0;
33 }

运行结果:     

str1 :123
str2 :6589thea
9th
str3 :ea
i3 :0

如果12行注掉的话, str2就是1236589thea,  注意24~26行,read是一个input操作,是streamsteam继承自istream的,  第22行  ss.ignore(3), 这个方法是也是stringstream从 istream继承过来的, 还有26行的write,这个是ostream定义的,这三个方法都是属于unformated这一组的(见下面)

参考:http://www.cplusplus.com/reference/iostream/

stream用来关联至可以实际作输入输出的实体,而stream中的character是一个一个的,按顺序的(sequence of characters),可以稍微想像一下,一个管道连着一个黑洞吧  ,因而所有对stream的output和input都被分为了两类formated, unformated, 而formated就是 operator<< (output)和 operator>>(input), 拿operator<<来说,它在ostream中重载了几组函数,又全局重载了一组 , 参看:http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/

1. 这个库中有些什么东西

   首先是basic class template,  其有两个模板参数,一个是character的类型,库中对这些模板类做了两种实例,一个character类型为char, 一个为wchar_t, 上图为char型的命名和结构图, 而class template的名称是上面这些类名加上 basic_ ,  ios_base中有一些和模板参数无关的的有io stream都有的成员, 而ios是和模板参数相关的所有io stream都有的成员,ios_base中有比如对flags, state flags的操作, ios中有对特定状态位的检测

2 streamstream, fstream本身提供的成员都很少,streamstream主要是  str(),   fstream主要是open(),close(), is_open(),  从istream和ostream继承了很多过来,  每一个stream应该都有一个stream buffer,  ios::rdbuf这个方法就提供了得到这个buffer的pointer, 而从streambuf又派生了stringbuf和filebuf,  <fstream>和<sstream>中的类用 rdbuf()会得到自己的filebuf和stringbuf (这些就是暂时写的,还不清楚其实),  streambuf是一个abstract base class (还没有搞清楚这个buffer类和stream类的关系)

3 以上的iostream库的设计就用到了 多继承和virtual inheritance 如下,  以下摘自 inside c++ object model  , 3.4节

1 class ios {...};
2 class istream : public virtual ios {...};
3 class ostream: public virtual ios{...};
4 class iostream: public istream, public ostream {...};
原文地址:https://www.cnblogs.com/livingintruth/p/2516388.html