【C++ Primer Plus习题】17.5

大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←

问题:

解答:

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <windows.h>
using namespace std;

int main()
{
	SetConsoleOutputCP(CP_UTF8);
	
	ifstream fin_mat("mat.txt", ios_base::in);
	ifstream fin_pat("pat.txt", ios_base::in);

	string guest;
	set<string>mat_guest, pat_guest, guest_set;
	if (!fin_mat.is_open() || !fin_pat.is_open())
	{
		cout << "Error open files." << endl;
		exit(EXIT_FAILURE);
	}
	while (getline(fin_mat,guest)&&guest.size()>0)
	{
		mat_guest.insert(guest);
	}
	cout << "\nMat's friends are: \n";
	for (auto pd = mat_guest.begin(); pd != mat_guest.end(); pd++)
	{
		cout << *pd << " ";
	}
	while (getline(fin_pat,guest)&&guest.size()>0)
	{
		pat_guest.insert(guest);
	}
	cout << "\nPat's friends are: \n";
	for (auto pd = pat_guest.begin(); pd != pat_guest.end(); pd++)
	{
		cout << *pd << " ";
	}
	fin_mat.close();
	fin_pat.close();

	guest_set.insert(mat_guest.begin(), mat_guest.end());
	guest_set.insert(pat_guest.begin(), pat_guest.end());

	ofstream fout("guest.txt", ios_base::out);
	if (!fout.is_open())
	{
		cout << "Error open file." << endl;
		exit(EXIT_FAILURE);
	}

	for (auto pd = guest_set.begin(); pd != guest_set.end(); pd++)
	{
		fout << *pd << " ";
	}
	fout.close();

	ifstream fin("guest.txt", ios_base::in);
	if (!fin.is_open())
	{
		cout << "Error open file." << endl;
		exit(EXIT_FAILURE);
	}
	cout << "\nAll Guest list: \n";
	while (getline(fin,guest)&&guest.size()>0)
	{
		cout << guest << " ";
	}
	cout << endl;
	fin.close();

	return 0;
}

运行结果:



考查点:

  • set容器
  • 读写文件

注意:

  • 字符问题,文件字符要与控制台字符一样才行,不然会出现乱码.

  • set容器的特点:

2024年9月22日16:13:28

相关推荐
敖行客 Allthinker几秒前
Go 语言中 panic 和 recover 的代价:性能与设计的权衡
开发语言·后端·golang
AnalogElectronic19 分钟前
整理一下arcGis desktop版本软件, 从入门到精通需要学习的知识点
学习·arcgis
osir.39 分钟前
2025天梯训练1
c++·多关键字最短路
Zach_yuan1 小时前
list的模拟实现
c++·list
胡桃不是夹子1 小时前
学会了蛇形矩阵
c++·算法·矩阵
今天也想MK代码1 小时前
rust编程实战:实现3d粒子渲染wasm
开发语言·rust·wasm
结衣结衣.1 小时前
【Qt】自定义信号和槽函数
开发语言·c++·qt·c++11
派阿喵搞电子1 小时前
轻量级 Transformer 架构&多模态预训练框架
学习
一弓虽1 小时前
maven学习
java·学习·github·maven
尘鹄2 小时前
一文讲懂Go语言如何使用配置文件连接数据库
开发语言·数据库·后端·golang