定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上c++
时间: 2024-03-10 16:46:43 浏览: 67
linux C++ 文本文件创建写入以及读取
4星 · 用户满意度95%
以下是示例代码,其中Person类需要根据具体需求自行定义:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
// Person类定义
class Person {
public:
string name;
int age;
string gender;
Person(string n, int a, string g) {
name = n;
age = a;
gender = g;
}
};
// 创建文件并写入n个Person对象
void createFile(string fileName, int n) {
ofstream outFile(fileName);
if (!outFile.is_open()) {
cout << "Error: cannot create file " << fileName << endl;
return;
}
for (int i = 0; i < n; i++) {
string name;
int age;
string gender;
cout << "Enter name for person " << i+1 << ": ";
cin >> name;
cout << "Enter age for person " << i+1 << ": ";
cin >> age;
cout << "Enter gender for person " << i+1 << ": ";
cin >> gender;
Person p(name, age, gender);
outFile << p.name << " " << p.age << " " << p.gender << endl;
}
outFile.close();
}
// 读取文件并显示内容
void readFile(string fileName) {
ifstream inFile(fileName);
if (!inFile.is_open()) {
cout << "Error: cannot open file " << fileName << endl;
return;
}
vector<Person> persons;
string line;
while (getline(inFile, line)) {
string name;
int age;
string gender;
stringstream ss(line);
ss >> name >> age >> gender;
Person p(name, age, gender);
persons.push_back(p);
}
inFile.close();
for (int i = 0; i < persons.size(); i++) {
cout << "Person " << i+1 << ": " << endl;
cout << "Name: " << persons[i].name << endl;
cout << "Age: " << persons[i].age << endl;
cout << "Gender: " << persons[i].gender << endl;
}
}
int main() {
string fileName = "person.txt";
int n;
cout << "Enter the number of persons: ";
cin >> n;
createFile(fileName, n);
cout << "File created successfully!" << endl;
cout << "Press any key to read file..." << endl;
getchar();
readFile(fileName);
return 0;
}
```
在运行程序时,会提示用户输入n个Person对象的信息,然后将这些信息写入文件中。再通过readFile函数读取文件内容并显示在屏幕上。
阅读全文