本章大意
介绍了标准IO库即其相关的使用
细节摘录
0. 简单的IO控制流层次
1. 复制,赋值均不能够为IO对象
2. 三种刷新缓冲区的方法 a flush ends endl操纵符 b unitbuf操纵符 c 将输入和输出绑定在一起
3. 文件输入输出标准步骤
4. 按模式打开文件
5. 字符串IO库
课后习题
1. 往文件,字符串中写入数据。
2. 形参和返回值对象不能为流,所以这个函数声明是错误的。
3.4:
6.
7.
8. 将使用continue的语句块放到循环最下面,就可以不用continue了。
9. 10.
11. 如果忽略这点,那么当再次打开的是同一文件时,文件指针就回指向还是原来的那个位置。调用了clear后,将会重置文件指针,使之指向开头。
12. 后面的打开文件操作会失败
13.
14. 略,简单。
15. 只要建好了字符流之后,直接带进函数即可。这种思想很棒。
16. 略,简单。
介绍了标准IO库即其相关的使用
细节摘录
0. 简单的IO控制流层次
1. 复制,赋值均不能够为IO对象
2. 三种刷新缓冲区的方法 a flush ends endl操纵符 b unitbuf操纵符 c 将输入和输出绑定在一起
3. 文件输入输出标准步骤
4. 按模式打开文件
5. 字符串IO库
课后习题
1. 往文件,字符串中写入数据。
2. 形参和返回值对象不能为流,所以这个函数声明是错误的。
3.4:
#include <iostream>
using namespace std;
istream& fun(istream & is)
{
string s;
while (is >> s) {
cout << s << endl;
}
is.clear(); // 注释或保留这句测试程序输出的不同结果。
return is;
}
int main()
{
if (fun(cin)) {
cout << "有效流" << endl;
}
else {
cout << "无效流" << endl;
}
return 0;
}
5. 可能是设备故障,输入结束,或者是某些可以修正的问题,对应的标签分别为badbit, eofbit, failbit。
6.
#include <iostream>
#include <fstream>
using namespace std;
void fun(istream & is) {
string s;
while (is) {
is >> s;
cout << s << endl;
}
}
int main()
{
ifstream ifs;
ifs.open("1");
if (!ifs) {
cout << "ERROR" << endl;
return 1;
}
else {
fun(ifs);
}
return 0;
}
7.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector<string> files;
files.push_back("1");
files.push_back("2");
files.push_back("3");
vector<string>::iterator it = files.begin();
while (it != files.end()) {
ifstream input(it->c_str());
if(!input) {
cout << "文件" << it->c_str() << "无法打开" << endl;
it++;
continue;
}
cout << "输出文件" << it->c_str() << endl;
string s;
while(input >> s) {
cout << s << endl;
}
++it;
}
return 0;
}
8. 将使用continue的语句块放到循环最下面,就可以不用continue了。
9. 10.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
vector<string> vs;
ifstream ifs;
ifs.open("1");
string tem;
while (ifs >> tem) { // 换成getline(ifs,tem)即可变成以行为单位存
vs.push_back(tem);
}
cout << "转存完毕,接下来输出容器vector:" << endl;
for (vector<string>::iterator it=vs.begin(); it!=vs.end(); it++) {
cout << *it << endl;
}
return 0;
}
11. 如果忽略这点,那么当再次打开的是同一文件时,文件指针就回指向还是原来的那个位置。调用了clear后,将会重置文件指针,使之指向开头。
12. 后面的打开文件操作会失败
13.
ofstream & open_file(ofstream &out, const string &file) {
out.close();
out.clear();
out.open(file.c_str());
return out;
}
14. 略,简单。
15. 只要建好了字符流之后,直接带进函数即可。这种思想很棒。
16. 略,简单。