在c++中定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上。
时间: 2024-03-10 22:47:46 浏览: 16
好的,以下是示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(const string& n = "", int a = 0) : name(n), age(a) { }
friend ostream& operator<<(ostream& os, const Person& p) {
os << p.name << " " << p.age;
return os;
}
friend istream& operator>>(istream& is, Person& p) {
is >> p.name >> p.age;
return is;
}
};
void createFile(const string& filename, int n) {
ofstream out(filename);
if (!out) {
cerr << "Failed to create file: " << filename << endl;
return;
}
for (int i = 0; i < n; ++i) {
string name = "Person" + to_string(i);
int age = rand() % 100;
Person p(name, age);
out << p << endl;
}
out.close();
}
void readFile(const string& filename) {
ifstream in(filename);
if (!in) {
cerr << "Failed to read file: " << filename << endl;
return;
}
Person p;
while (in >> p) {
cout << p << endl;
}
in.close();
}
int main() {
createFile("person.txt", 10);
readFile("person.txt");
return 0;
}
```
这个例子中,我们定义了一个 `Person` 类,其中包含了姓名和年龄两个数据成员,以及输出和输入运算符重载函数。我们还定义了两个函数 `createFile` 和 `readFile`,前者用于创建一个文本文件,并将 `n` 个 `Person` 对象写入文件,后者用于读取文件中的信息并将其显示在屏幕上。在主函数中,我们首先调用 `createFile` 函数创建一个名为 `person.txt` 的文件,并写入 10 个随机生成的 `Person` 对象,然后调用 `readFile` 函数读取并显示文件中的信息。