用c++定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上。
时间: 2024-03-10 14:47:44 浏览: 26
好的,我可以帮你解决这个问题。
首先,我们需要定义一个Person类,以便我们能够将n个Person对象写入文件中。
```c++
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
string getName() {
return name;
}
int getAge() {
return age;
}
};
```
接下来,我们可以定义函数createFile和readFile。
```c++
void createFile(int n) {
ofstream file("person.txt");
for (int i = 0; i < n; i++) {
string name;
int age;
cout << "Enter the name of the person: ";
cin >> name;
cout << "Enter the age of the person: ";
cin >> age;
Person p(name, age);
file << p.getName() << " " << p.getAge() << endl;
}
file.close();
}
void readFile() {
ifstream file("person.txt");
string name;
int age;
while (file >> name >> age) {
cout << "Name: " << name << ", Age: " << age << endl;
}
file.close();
}
```
在createFile函数中,我们打开一个名为“person.txt”的文件,并循环n次,从用户那里获取每个Person对象的名称和年龄,然后将其写入文件中。最后,我们关闭文件。
在readFile函数中,我们打开名为“person.txt”的文件,并循环遍历每个Person对象的名称和年龄,并将其输出到屏幕上。最后,我们关闭文件。
现在,我们可以在主函数中调用这些函数。
```c++
int main() {
int n;
cout << "Enter the number of persons: ";
cin >> n;
createFile(n);
readFile();
return 0;
}
```
在主函数中,我们从用户那里获取要创建的Person对象的数量,然后调用createFile函数来创建文件并写入Person对象。接下来,我们调用readFile函数来读取文件并将其输出到屏幕上。
这样就完成了用c++定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上的任务。