相关流的定义以及三种分类
首先对输入以及输出流的定义,这里iostream的输入以及输出是内存相对于io设备来说的,比如cin和cout(这两个操作是针对内存以及io设备——屏幕=进行操作的):
- cin就表示从屏幕中输出到字符串或者其他类型(内存中数据);
- cout就表示从从字符或者其他类型(内存中数据)输出到屏幕上;
string str="";
cin>>str;
cout<<str<<
而文件流就是针对文件和内存数据来说的,
总体的IO分为三种流的类别,分别如下:
其实cin就是istream的对象,而cout就是ostream的实例化对象,他们具有>>以及<<运算符,同理其他几个也具有一样的运算符,比如ifstream就具有>>运算符,而ofstream就具有<<运算符。可以看下面的示例,分别通过文件流读入或者写入相关的文件:
常见流的简单示例演示(均在ubuntu中实现)
iostream
常见的cin以及cout相信都比较熟悉。
ifstream的示例
运行前的布局:
#include<iostream>
using namespace std;
#include<fstream>
#include<string.h>
#include<string>
int main() {
const char* str1 = "I Love You";
int n[5];
ifstream in("xxx.xxx");
string str_in="str_in";
in>>str_in;
cout<<str_in<<endl;
ofstream out("yyy.yyy");
out<<str1;
out.write(str1, strlen(str1));//把字符串str1全部写到yyy.yyy中
in.read((char*)n, sizeof(n));//从xxx.xxx中读取指定个整数,注意类型转换
in.close(); out.close();
}
运行之后str_in被xxx.xxx第一行的内容覆盖了,并且通过输出流将str1的内容两次输入到了文件yyy.yyy中。
sstream的示例:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str = "hello world I am very happy!";
stringstream sstream(str); // sstream<< 将str的内容加入内存流,这是其构造函数做的事情
while (sstream)
{
string substr;
sstream >> substr; //从内存中将内容写进substr
cout << substr << endl; //也可vec.push_back(substr);
}
return 0;
}