11-3:
1 #include <iostream>
2 #include <fstream>
3
4 using namespace std;
5
6 int main()
7 {
8 ofstream out("test1.txt");
9 out << "已成功写入文件!" << endl;
10 out.close();
11 return 0;
12 }
截图略……
11-4
1 #include <iostream>
2 #include <fstream>
3 #include <string>
4
5 using namespace std;
6
7 int main()
8 {
9 string x;
10 ifstream in("E:\\程序\\题目\\题目6\\11-3\\11-3\\test1.txt");
11 in >> x;
12 in.close();
13 cout << x << endl;
14 return 0;
15 }
截图略……
11-7
1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 ios_base::fmtflags original_flags = cout.flags(); //保存当前参数设置
8 cout << 812 << '|';
9 cout.setf(ios_base::left, ios_base::adjustfield); //左对齐
10 cout.width(10); //设置单次输出的域宽
11 cout << 813 << 815 << '/n';
12 cout.unsetf(ios_base::adjustfield); //清除左对齐
13 cout.precision(2);
14 cout.setf(ios_base::uppercase | ios_base::scientific); //科学计数法
15 cout << 831.0;
16 cout.flags(original_flags); //恢复原先格式
17 return 0;
18 }
截图略……
应用练习1:
1 #include <iostream>
2 #include <cstdlib>
3 #include <ctime>
4 #include <fstream>
5 #include <string>
6
7 using namespace std;
8
9 int main()
10 {
11 srand(time(NULL));
12 string x;
13 for (int i = 1; i <= 5; ++i)
14 {
15 int n = rand() % 16 + 1;
16 ifstream in("list.txt");
17 if (!in)
18 {
19 cerr << "open error!" << endl;
20 return 1;
21 }
22 for (int i = 1; i < n; i++)
23 in.ignore(1000, '\n');
24 getline(in, x);
25 in.close();
26 cout << x << endl;
27 }
28 return 0;
29 }
截图:

应用练习2:
1 #include <iostream>
2 #include <string>
3 #include <fstream>
4
5 using namespace std;
6
7 int main()
8 {
9 string a;
10 cout << "Please enter the name of file: ";
11 cin >> a;
12 ifstream in(a);
13 if (!in)
14 {
15 cerr << "open error!" << endl;
16 return 1;
17 }
18 int number = 0, letter = 0, line = 0;
19 string x;
20 while (getline(in, x))
21 {
22 number += x.length();
23 bool flag = true;
24 for (int i = 0; i < x.length(); i++)
25 {
26 if (x[i] == ' '|| x[i] == '\n')
27 {
28 if (flag == false)
29 {
30 letter++;
31 flag = true;
32 }
33 }
34 else if (flag == true)
35 flag = false;
36 }
37 if (flag == false)
38 letter++;
39 line++;
40 }
41 in.close();
42 cout << "字符数:" << number << endl;
43 cout << "单词数:" << letter << endl;
44 cout << "行数:" << line << endl;
45 return 0;
46 }
截图:

实验总结:这为我们以后系统编程提供了极大的方便,当项目比较大时,用文件读入数据大大节省了我们的时间。
之前我在制作游戏,读取相关数据是也用到相关知识,学习后,了解的更加完善了。
另外说一句,list原文件莫名其妙的乱码了……
来源:https://www.cnblogs.com/rq1b-qsy666/p/9205682.html