譚浩強C++課後習題42——ASCII文件操作(1)
題目描述:從鍵盤讀入一行字符,把其中的字母字符依次存放在磁盤文件d1.txt中,再把它從磁盤文件讀入程序,將其中的小寫字母改寫爲大寫字母,再存入磁盤文件d2.txt中。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//save_to_file函數爲將從鍵盤輸入的字符串中的字母存入磁盤文件,文件名由參數傳遞。
void save_to_file(string filename) {
//定義輸出文件流對象
ofstream outfile(filename, ios::out);
//判斷文件有沒有打開成功
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
string str;
//從鍵盤中輸入字符串
getline(cin, str);
//判斷每一個字符,是否是字母,如果是就寫入文件。
for (int i = 0;i < str.length();i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
outfile << str[i];
}
}
//最後關閉文件。
outfile.close();
}
//get_from_file函數用於讀取第一個文件中的字符,將所有字母變爲大寫再寫入第二個文件。
void get_from_file(string filename1, string filename2) {
//定義輸入文件流
ifstream infile(filename1, ios::in | ios::_Nocreate);
if (!infile) {
cerr << "open error!" << endl;
exit(1);
}
//定義輸出文件流
ofstream outfile(filename2, ios::out);
if (!outfile) {
cerr << "open error!" << endl;
exit(1);
}
//循環提取第一個文件中的字母,轉換爲大寫字母后存入第二個文件。
char c;
while (infile.get(c)) {
if (c >= 'a' && c <= 'z') {
c = c - 32;
}
outfile << c;
}
//最後關閉兩個文件。
infile.close();
outfile.close();
}
int main() {
save_to_file("d1.txt");
get_from_file("d1.txt", "d2.txt");
return 0;
}
運行測試結果: