C++:【练习题】输入输出流

习题1

1.1 题目:

杰克船长挖掘到一个宝藏,里面有各种各样的财宝,每种财宝一堆,杰克船长打算每次将两堆财宝合并,直到将这些财宝合并为一堆,显然,经过n-1次合并之后,财宝会成为1堆,假定消耗的体力为两堆财宝的重量之和,为了将这批宝藏搬运到船上,杰克船长必须保证合并时花费的体力最少,你的任务是设计合并方案,计算出最小的体力消耗值。
输入:第一行一个整数N表示有N组测试数据,
接下来的N组测试数据,第一行整数M表示有M种财宝,下一行包括M个整数,表示每种财宝的重量。
输出:消耗的最小体力值

2
3
5 1 7
6
5 8 4 11 9 13 

其执行结果为:

19
126

1.2 解题思路:

  • 将每个类别的珠宝重量用vector存储。
  • 实现原理为将最小重量的两堆珠宝整合,新成新的一堆珠宝。
  • 重复上述步骤直至珠宝变成一堆。

1.3 代码及注释:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int main() {
	// 输入测试次数
	int test_times;
	cin >> test_times;
	// 用vector来存储数据
	vector<int>* list = new vector<int>[test_times];
	for (int i = 0; i < test_times; i++) {
		// 输入类别
		int classification;
		cin >> classification;
		// 输入每个类别的重量
		for (int j = 0; j < classification; j++) {
			int weight;
			cin >> weight;
			list[i].push_back(weight);
		}
		// 进行排序
		sort(list[i].begin(), list[i].end());
	}
	for (int i = 0; i < test_times; i++) {
		int size = list[i].size();
		// 输出结果
		int result = 0;
		if (size > 1) {
			while (size > 1) {
				int w = list[i][0] + list[i][1];
				result += w;
				list[i].erase(list[i].begin(), list[i].begin() + 2);
				list[i].push_back(w);
				sort(list[i].begin(), list[i].end());
				size--;
			}
			cout << result << endl;
		}
		else {
			cout << result;
		}	
	}
	return EXIT_SUCCESS;
}

1.4 程序运行结果分析:

2
3
5 1 7
6
5 8 4 11 9 13
19
126

D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project1\Debug\Project1.exe (进程 37360)已退出,代码为 0。
按任意键关闭此窗口. . .

验证可得程序执行正确。

习题2

2.1 题目:

按字典序统计下面这段文字中单词出现的次数

It was the best of times, and it was the worst of times. It was the age of wisdom, and it was the age of foolishness. It was the epoch of belief, and it was the epoch of incredulity. It was the season of light, and it was the season of darkness. It was the spring of hope, and it was the winter of despair. We had everything before us, and we had nothing before us. We were all going direct to Heaven, and we were all going direct the other way. In short, the period was so far like the present period. That some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.

2.2 解题思路:

  • 利用map类型存储单词和出现次数,map采用hash存储,类似字典类型。
  • 利用getline对文字段进行输入。
  • 输出并展示最终的统计结果。

2.3 代码及注释:

#include <iostream>
#include <iomanip>
#include <string>
#include <map>

using namespace std;

int main() {
	// 利用字典类型map存储key和value
	map<string, int> dict;
	string input;
	// 输入文字段
	getline(cin, input, '\n');
	string word = "";
	// 对文字段进行分词
	for (int index = 0; index < input.size(); index++) {
		if (input[index] == ',' || input[index] == ' ' || input[index] == '.') {
			if (word.size() > 0) {
				// 每出现一次,次数进行累加
				++dict[word];
				word = "";
			}
		}
		else {
			word = word + input[index];
		}
	}
	// 统计出现的单词和次数
	cout << endl << "     Dictionary Show     " << endl;
	for (auto i = dict.begin(); i != dict.end(); i++) {
		cout << "key : " << std::left << setw(12) << i->first;
		cout << " value : " << i->second << endl;
	}
	return EXIT_SUCCESS;
}

2.4 程序运行结果分析:

验证结果如下:

It was the best of times, and it was the worst of times. It was the age of wisdom, and it was the age of foolishness. It was the epoch of belief, and it was the epoch of incredulity. It was the season of light, and it was the season of darkness. It was the spring of hope, and it was the winter of despair. We had everything before us, and we had nothing before us. We were all going direct to Heaven, and we were all going direct the other way. In short, the period was so far like the present period. That some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.

     Dictionary Show
key : Heaven       value : 1
key : In           value : 1
key : It           value : 5
key : That         value : 1
key : We           value : 2
key : age          value : 2
key : all          value : 2
key : and          value : 7
key : authorities  value : 1
key : before       value : 2
key : being        value : 1
key : belief       value : 1
key : best         value : 1
key : comparison   value : 1
key : darkness     value : 1
key : degree       value : 1
key : despair      value : 1
key : direct       value : 2
key : epoch        value : 2
key : everything   value : 1
key : evil         value : 1
key : far          value : 1
key : foolishness  value : 1
key : for          value : 2
key : going        value : 2
key : good         value : 1
key : had          value : 2
key : hope         value : 1
key : in           value : 1
key : incredulity  value : 1
key : insisted     value : 1
key : it           value : 5
key : its          value : 2
key : light        value : 1
key : like         value : 1
key : noisiest     value : 1
key : nothing      value : 1
key : of           value : 12
key : on           value : 1
key : only         value : 1
key : or           value : 1
key : other        value : 1
key : period       value : 2
key : present      value : 1
key : received     value : 1
key : season       value : 2
key : short        value : 1
key : so           value : 1
key : some         value : 1
key : spring       value : 1
key : superlative  value : 1
key : the          value : 14
key : times        value : 2
key : to           value : 1
key : us           value : 2
key : was          value : 11
key : way          value : 1
key : we           value : 2
key : were         value : 2
key : winter       value : 1
key : wisdom       value : 1
key : worst        value : 1

D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project2\Debug\Project2.exe (进程 41380)已退出,代码为 0。
按任意键关闭此窗口. . .

因此,程序执行正确。

习题3

3.1 题目:

编写一个程序,统计每个英文诗词中的诗歌行数和单词个数。
要求:
1、输入使用Poems.txt文件,链接:https://pan.baidu.com/s/14USpQ_VdoFWaNEgxkRuILQ 提取码:st48
2、输出需要格式化输出,每首诗输出一行,每行格式为:T:诗的名称 + P:作者名称 + L:行数 + W:单词数。其中所有的T:P:L:W:都应该上下对齐,标题和诗人左对齐,数字为宽度为5字符的右对齐。参考下图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PJ5VI31j-1603458897834)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529195456629.png)]

3、诗中的缩写,如I’m, I’ll 等,理解成用’分隔的两个单词。

3.2 解题思路:

  • 打开Poems.txt文件。
  • 输入文件内每行的内容进行判断。
  • 编写GetWords函数进行统计单词。
  • 对结果进行格式化的输出。

3.3 代码及注释:

#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>

using namespace std;

// 统计字数函数
int GetWords(string row) {
	int size = row.size();
	int num = 1;
	for (int index = 0; index < size; index++) {
		if (row[index] == ' ' || row[index] == '\'')
			num++;
		if (row[index] == '-')
			num--;
	}
	return num;
}

int main() {
	// 读取每行的数据存储在str内
	string str;
	int size = 0;
	// 读取文件
	ifstream infile("Poems.txt");

	// 循环读取文件的内容
	while (getline(infile, str)) {
		size = str.size();
		// 标题
		string title = str.substr(7, size - 1);
		cout << "T: " << std::left << setw(28) << title;

		getline(infile, str);
		size = str.size();
		// 作者
		string author = str.substr(6, size - 1);
		cout << "P: " << std::left << setw(28) << author;

		getline(infile, str);
		getline(infile, str);

		// 字数和行数
		int num = 0, row = 0;
		while (str.size() != 0) {
			row++;
			num += GetWords(str);
			getline(infile, str);
		}
		cout << "L:" << std::right << setw(5) << row;
		cout << setw(5) << "W:" << std::right << setw(5) << num << endl;
	}
	// 关闭文件
	infile.close();
	return EXIT_SUCCESS;
}

3.4 程序运行结果分析:

结果如下:

T: My Life Has Been the Poem   P: Henry David Thoreau         L:    2   W:   19
T: I'm Nobody! Who Are You?    P: Emily Dickinson             L:    8   W:   47
T: Dreams                      P: Robert Herrick              L:    3   W:   19
T: No Man Is An Island         P: John Donn                   L:   13   W:   94

D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project3\Debug\Project3.exe (进程 42620)已退出,代码为 0。
按任意键关闭此窗口. . .

因此,程序执行正确。

习题4

4.1 题目:

将练习题1中,自己写的代码文件作为输入文件,为源代码中每行开头添加一个行号和冒号,并在终端打印输出。
要求:

  • 1、行号右对齐,固定列宽为3,高位填充0。
  • 2、冒号为英文冒号。
  • 3、实验报告中要有源代码和加了行号的代码的对比截图。

4.2 解题思路:

  • 打开文件。
  • 用getline函数每行输入文件内容。
  • 用setfill函数进行填充0。
  • 关闭文件。

4.3 代码及注释:

#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>

using namespace std;

int main() {
	// 打开文件
	ifstream infile("input.txt");
	int row = 0;
	string content;
	while (getline(infile, content)) {
		row++;
		// 输出行数
		cout << std::right << setw(3) << setfill('0') << row << ":";
		// 输出每行的内容
		cout << content << endl;
	}
	// 关闭文件
	infile.close();
	return EXIT_SUCCESS;
}

4.4 程序运行结果分析:

截图如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kwxZbMzk-1603458897840)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529223454218.png)]

输出结果如下:

001:#include<iostream>
002:#include<iomanip>
003:#include<fstream>
004:#include<string>
005:
006:using namespace std;
007:
008:// 统计字数函数
009:int GetWords(string row) {
010:    int size = row.size();
011:    int num = 1;
012:    for (int index = 0; index < size; index++) {
013:            if (row[index] == ' ' || row[index] == '\'')
014:                    num++;
015:            if (row[index] == '-')
016:                    num--;
017:    }
018:    return num;
019:}
020:
021:int main() {
022:    // 读取每行的数据存储在str内
023:    string str;
024:    int size = 0;
025:    // 读取文件
026:    ifstream infile("Poems.txt");
027:
028:    // 循环读取文件的内容
029:    while (getline(infile, str)) {
030:            size = str.size();
031:            // 标题
032:            string title = str.substr(7, size - 1);
033:            cout << "T: " << std::left << setw(28) << title;
034:
035:            getline(infile, str);
036:            size = str.size();
037:            // 作者
038:            string author = str.substr(6, size - 1);
039:            cout << "P: " << std::left << setw(28) << author;
040:
041:            getline(infile, str);
042:            getline(infile, str);
043:
044:            // 字数和行数
045:            int num = 0, row = 0;
046:            while (str.size() != 0) {
047:                    row++;
048:                    num += GetWords(str);
049:                    getline(infile, str);
050:            }
051:            cout << "L:" << std::right << setw(5) << row;
052:            cout << setw(5) << "W:" << std::right << setw(5) << num << endl;
053:    }
054:    // 关闭文件
055:    infile.close();
056:    return EXIT_SUCCESS;
057:}

D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project4\Debug\Project4.exe (进程 40772)已退出,代码为 0。
按任意键关闭此窗口. . .

因此,程序执行正确。

习题5

5.1 题目:

练习题1中的文件夹中的另一个文件 Students.txt里面存放的是由excel另存为txt的文本文件,excel内容如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-59jX5bCC-1603458897844)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529224930378.png)]

请是用输入输出流章节所学知识,将数据从txt文件中读出,完成以下要求后输出到StandardStudent.txt文件中。要求如下:

  • 1、计算尺英语、数学、计算机三科的平均分,保留两位小数替换掉Avgerage列中个0,数值应小数点对齐。
  • 2、将Tuition(学费)中的数据用科学计数法输出。

5.2 解题思路:

  • 打开文件。
  • 适当利用不同数据类型进行读取。
  • 利用格式化按照题目要求进行写入。
  • 关闭文件。
  • 打开生成文件进行验证。

5.3 代码及注释:

#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>

using namespace std;

int main() {
	// 打开文件
	ifstream file1("Students.txt");
	ofstream file2("StandardStudent.txt");
	string content;
	getline(file1, content);
	file2 << std::left << setw(5) << "ID" << setw(10) << "Name";
	file2 << std::right << setw(10) << "English" << setw(10) << "Math" << setw(10) << "Computer";
	file2 << std::right << setw(10) << "Average" << setw(10) << "Tuition" << endl;
	while (file1 >> content) {
		// 对信息进行格式化输出
		string name;
		int num1, num2, num3;
		double average, tuition;
		file1 >> name >> num1 >> num2 >> num3 >> average >> tuition;
		average = (num1 + num2 + num3) / 3.0;
		file2 << std::left << setw(5) << content << setw(10) << name
			<< std::right << setw(10) << num1 << setw(10) << num2 << setw(10) << num3;
		file2.precision(2);
		file2 << setw(10) << std::fixed << average;
		file2 << setw(10) << std::scientific << tuition << endl;
	}
	// 关闭文件
	file1.close();
	file2.close();

	return EXIT_SUCCESS;
}

5.4 程序运行结果分析:

截图效果如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GnGIK1T2-1603458897845)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529233857573.png)]

由实验结果可知:程序执行正确。

习题6

6.1 题目:

将练习题1中使用的Poems.txt中的每个英文诗歌提取出来,并单独存到一个文本文件中,一首诗对应一个文件。
要求

  • 1、文件名为“诗歌名__诗人名.txt”的形式(两个连续的下划线隔开)。
  • 2、实验报告中要有文件名的截图和文件内容的截图。
  • 3、诗歌名称中的标点符号在转换成文件名时应该去掉。

6.2 解题思路:

  • 打开Poems.txt文件。
  • 获取诗歌名称和作者名称。
  • 生成文件的相对路径。
  • 用replace函数对路径内的标点符号进行删除。
  • 对路径文件内写入诗歌内容。
  • 验证最后的结果。

6.3 代码及注释:

#include<iostream>
#include<algorithm>
#include<iomanip>
#include<fstream>
#include<string>

using namespace std;

int main() {
	// 读取每行的数据存储在str内
	string str;
	int size = 0;
	// 读取文件
	ifstream infile("Poems.txt");

	// 循环读取文件的内容
	while (getline(infile, str)) {
		size = str.size();
		// 标题
		string title = str.substr(7, size - 1);

		getline(infile, str);
		size = str.size();
		// 作者
		string author = str.substr(6, size - 1);

		// 文件名
		string name = title + "__" + author + ".txt";
		// 替换出现的标点符号
		replace(name.begin(), name.end(), '!', ' ');
		replace(name.begin(), name.end(), '?', ' ');
		ofstream outfile(name);
		cout << name << endl;

		getline(infile, str);
		getline(infile, str);

		// 输入内容
		while (str.size() != 0) {
			outfile << str << endl;
			getline(infile, str);
		}
		// 关闭文件
		outfile.close();
	}
	// 关闭文件
	infile.close();
	return EXIT_SUCCESS;
}

6.4 程序运行结果分析:

截图效果如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NgS6F9I4-1603458897846)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200530001447394.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iP44iLcb-1603458897847)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200530115041672.png)]

由结果得,程序执行正确。

习题7

7.1 题目:

编写一个程序,将5种商品的商品号、商品名、单价和数量写入二进制文件f.bin中,然后将该文件中的数据读到数组中,并将其输出到屏幕上。

7.2 解题思路:

  • 构造商品如下:

    idnamenumberprice
    001可乐8112.22
    002电池2099.78
    003纸巾3478
    004面包1210.07
    005烤鸡2516.35
  • 构造struct来存储商品信息。

  • 利用write函数将信息写入二进制文件内。

  • 利用read函数对二进制文件进行读取。

  • 保存在数组内。

  • 将结果展示。

7.3 代码及注释:

#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>

using namespace std;

// 商品信息
struct commodity{
	string id;
	string name;
	double price;
	int num;
	commodity(string id_, string name_, double price_, int num_) : 
		id(id_), name(name_), price(price_), num(num_) {}
	commodity() {}
};

// 写入到二进制文件内
void WriteFile(string filename) {
	commodity a("001", "可乐", 12.22, 81);
	commodity b("002", "电池", 99.78, 20);
	commodity c("003", "纸巾", 21.57, 34);
	commodity d("004", "面包", 10.07, 12);
	commodity e("005", "烤鸡", 16.35, 25);
	ofstream file(filename, ios::binary);
	file.write((char*)(&a), sizeof(a));
	file.write((char*)(&b), sizeof(a));
	file.write((char*)(&c), sizeof(a));
	file.write((char*)(&d), sizeof(a));
	file.write((char*)(&e), sizeof(a));
	file.close();
}

// 从二进制文件内写出信息
void ReadFile(string filename) {
	ifstream file(filename, ios::binary);
	// 数组存储信息
	commodity s[5];
	// 循环导入信息
	for (int index = 0; index < 5; index++) {
		file.read((char*)(&s[index]), sizeof(s[index]));
	}
	file.close();

	cout << std::left << setw(8) << "ID" << setw(8) << "Name" << setw(8) << "Num" << setw(8) << "Price" << endl;
	// 循环展示信息
	for (int index = 0; index < 5; index++) {
		cout << setw(8) << s[index].id << setw(8) << s[index].name << setw(8) <<
			s[index].num << setw(8) << s[index].price << endl;
	}
}

int main() {
	// 二进制文件文件路径
	string path = "bf.bin";
	//WriteFile(path);
	ReadFile(path);
	return EXIT_SUCCESS;
}

7.4 程序运行结果分析:

运行结果如下:

ID      Name    Num     Price
001     可乐    81      12.22
002     电池    20      99.78
003     纸巾    34      21.57
004     面包    12      10.07
005     烤鸡    25      16.35

请按任意键继续. . .

因此,程序执行正确。

习题8

8.1 题目:

编写一个程序从文件f.bin(第1题已建立的文件)中读出任意一种商品的数据并输出到屏幕上。比如输入整数2,则输出第二种商品的信息

8.2 解题思路:

  • 利用读取特点,读取二进制文件中第n个商品的信息。
  • 对商品信息进行格式化输出。
  • 验证结果的准确性。

8.3 代码及注释:

#include<iostream>
#include<string>
#include<fstream>
#include<iomanip>

using namespace std;

// 商品信息
struct commodity{
	string id;
	string name;
	double price;
	int num;
	commodity(string id_, string name_, double price_, int num_) : 
		id(id_), name(name_), price(price_), num(num_) {}
	commodity() {}
};

// 从二进制文件内写出信息
void ReadFile(string filename, int num) {
	ifstream file(filename, ios::binary);
	// 存储信息
	commodity s;
	// 寻找第num种商品的信息
	int index = 0;
	while (file.read((char*)(&s), sizeof(s))) {
		index++;
		if (index == num)
			break;
	}
	file.close();

	// 显示信息
	if (index == num) {
		cout << std::left << setw(8) << "ID" << setw(8) << "Name" << setw(8) << "Num" << setw(8) << "Price" << endl;
		cout << setw(8) << s.id << setw(8) << s.name << setw(8) <<
			s.num << setw(8) << s.price << endl;
	}
	else {
		cout << "No Find!" << endl;
	}


}

int main() {
	// 二进制文件文件路径
	string path = "bf.bin";
	int num;
	cin >> num;
	ReadFile(path, num);
	return EXIT_SUCCESS;
}

8.4 程序运行结果分析:

我们查找第二件商品(存在)和第六件商品(不存在)

结果如下:

2
ID      Name    Num     Price
002     电池    20      99.78

请按任意键继续. . .
6
No Find!

请按任意键继续. . .

验证测试实验表明,程序执行正确。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值