编写一个程序,采用“>>”和“<<”运算符重载的方法,将文本文件f1.dat中的数据读到一个数组类Array的对象ob(4╳5大小)中,并显示出来,然后将ob写到f2.dat文件中;
假设f1.dat文件中的数据为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Array {
private:
int str[4][5];
public:
Array() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
str[i][j] = '\0';
}
}
}
Array& operator<<(ifstream& file) {
char s[1000];
//int a = 0;
int i = 0;
int j = 0;
while (file >> s) {
//a++; // a=20
int num = 0;
for (int k = 0; k < strlen(s); k++) {
num *= 10;
num += s[k] - 48;
}
str[i][j] = num;
j++;
if (j == 5) {
j = 0;
i++;
}
}
//cout << a;
return *this;
}
Array& operator>>(ofstream& file) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
file << str[i][j] << " ";
}
}
return *this;
}
void Display() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5;j++) {
cout << str[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Array A;
//A.Display();
ifstream ifs;
ofstream ofs;
ifs.open("f1.dat.txt", ios::in);
ofs.open("f2.dat.txt", ios::out);
A << ifs;
//A.Display();
A >> ofs;
ifs.close();
ofs.close();
return 0;
}
注:两个文件需要和CPP文件在同一文件里。