【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

相关推荐
a1117761 小时前
2FA 验证码生成器(github登录验证 app)
笔记·学习
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
fqbqrr1 小时前
2607C++,使用微软detours勾挂工具
c++
人邮异步社区1 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大2 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai2 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
এ慕ོ冬℘゜2 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript
执明wa2 小时前
LayoutInflater详解: XML是如何变成View的?
android·xml·开发语言·android studio
一次旅行3 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
你想知道什么?3 小时前
线性回归-学习笔记
笔记·学习·线性回归