IO库
C++ 在IO库中定义的类型支持从键盘、文件、控制台窗口进行输入输出等。
IO类
IO库类型和头文件
头文件 | 类型 |
---|---|
iostream | istream/ostream wistream/wostream iostream/wiostream |
fstream | ifstream/ofstream wifstream/wofstream fstream/wfstream |
sstream | istringstream/ostringstream wistringstream/wostringstream stringstream/wstringstream |
流类型 stream
文件类型 fstream
字符串类型 sstream
IO类型之间的关系
父类 | 子类 |
---|---|
istream | ifstream istringstream |
ostream | ofstream ostringstream |
IO对象无拷贝或赋值
IO流的状态
### 管理输出缓冲
一般原因
- 程序正常结束
- 缓冲区满
- 使用endl
- 一个输出流可能被关联到另一个流(输出流或输入流)
- unitbuf操作符
文件读写
常用功能
函数 | 功能 |
---|---|
fstream f(s.mode) | 按照指定模式打开文件 |
f.open(s) | 打开文件名为s的文件,并将文件与f绑定,返回void |
f.close() | 关闭与f相绑定的文件,返回void |
f.is_open() | 判断文件是否打开,若成功打开,返回True |
例程
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *arv[])
{
//write
ofstream file;
string path = "1.txt";
file.open("1.txt");
if (file.is_open())
{
file << "Hello World!";
}
else
{
cerr << "No data?!" << endl;
}
file.close();
//read
ifstream read_file;
read_file.open(path, ifstream::in);
string s;
if (! read_file.is_open())
{
exit(1);
}
while (! in.eof())
{
s = read_file.
}
return 0;
}
每次打开文件完成操作后必须进行关闭,除非在for循环内每次都新定义一个文件对象,那么就不用关闭,文件对象销毁同时则会自动关闭
文件模式
模式 | 说明 |
---|---|
in | 读方式 |
out | 写方式 |
app | 写操作,定位文件末尾 |
ate | 打开文件,定位文件末尾 |
trunc | 截断文件 |
binary | 以二进制方式进行IO |
用法示例
ofstream out("file.txt", ofstream::app)
string类
sstream特有操作
函数 | 说明 |
---|---|
sstream strm(s) | strm是sstream对象,且保存string s 的一个拷贝 |
strm.str() | 返回strm所保存的string的拷贝 |
strm.str(s) | 将string s 拷贝到strm中,返回void |
istringstream
#例程#
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct PersonInfo{
string name;
vector<string> phones;
};
string line, word;
vector<PersonInfo> people;
while(getline(cin, line))
{
PersonInfo info;
istringstream record(line);
record >> info.name;
while (record >> word)
{
info.phones.push_back(word);
}
people.push_back(info);
}
//得限定字符串输入个数,以便于跳出while循环
return 0;
}