1. 程式人生 > >C++程式設計題練習程式碼筆記

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;
}