C++程序设计题练习代码笔记

从文本文件old.txt读取字符,将其中的数字字符‘0’、‘1’、‘2’、‘3’、‘4’、‘5’、‘6’、‘7’、‘8’、‘9’ 分别用英文字母字符‘Z’、‘Y’、‘X’、‘W’、‘V’、‘U’、‘T’、‘S’、‘R’、‘Q’替换,其余字符不变,结果写入文本文件new.txt,并分别将两个文件内容输出屏幕。

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
	char ch;
	ifstream rch;
	rch.open("old.txt");						//打开文件old.txt
	if (! rch)									//文件出错处理
	{
		cout << "文件打不开!\n";
		return 0;								//文件出错,结束程序运行
	}
	ofstream wch("new.txt");					//建立文件new.txt
	if (! wch)									//文件出错处理
	{
		cout << "没有正确建立文件!" << endl;
		return 0;								//文件出错,结束程序运行
	}

	cout << "读取数字字符:" << endl;
	while (1)									//每次读取一条完整信息
	{
		rch >> ch;
		if (rch.eof())
		{
			rch.close();						//关闭文件old.txt
			break;								//跳出循环
		}
		cout << ch << setw(2);

		if (ch >= '0' && ch <= '9')
		{
			ch = 'Z' - (ch - 48);
			wch << ch;							//将新字符存入文件
		}
	}
	wch.close();								//关闭文件
	rch.clear();								//清除文件流的状态
	rch.open("new.txt");						//打开文件new.txt
	if (!rch)									//文件出错处理
	{
		cout << "文件打不开!\n";
		return 0;								//文件出错,结束程序运行
	}
	cout << endl << "读取新字符:" << endl;
	while (1)									//每次读取一条完整信息
	{
		rch >> ch;
		if (rch.eof())
		{
			rch.close();						//关闭文件new.txt
			break;								//跳出循环
		}
		cout << ch << setw(2);
	}
	cout << endl;
	return 0;
}

 

猜你喜欢

转载自blog.csdn.net/qq_37592750/article/details/82955459