定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上。
可以先定义一个Person类,然后在创建n个Person对象,写入文件后,再读取显示即可。
代码如下:
参考链接:
#include <iostream>
#include <string.h>
#include <fstream>
#include <iostream>
using namespace std;
// http://c.biancheng.net/view/2213.html
class Person{
public :
char name[20]; // 姓名
int age; // 年龄
// https://www.runoob.com/cplusplus/cpp-constructor-destructor.html
Person(); // 无参的构造方法
Person(char *name, int age); // 两个参数的构造方法
void say(); // 显示对象信息的函数
};
void Person::say(){
cout<<"姓名:"<<name<<",年龄:"<<age<<endl;
}
Person::Person(){
}
Person::Person(char *sname,int sage){
strcpy(name,sname);
age=sage;
}
void createFile(){
// https://runoob.com/cplusplus/cpp-files-streams.html
// https://blog.csdn.net/qq_44859843/article/details/125787789
// 创建文件输出流对象
ofstream outfile("person.txt",ios::binary);
if(!outfile){
cout<<"文件打开失败!"<<endl;
return ;
}
// 创建三个对象,用于写入文件
Person p1("张三",23);
Person p2("李四",24);
Person p3("王五",25);
// 把三个对象写入文件
// https://zhuanlan.zhihu.com/p/33040213
outfile.write(reinterpret_cast<char*>(&p1), sizeof(Person));
outfile.write(reinterpret_cast<char*>(&p2), sizeof(Person));
outfile.write(reinterpret_cast<char*>(&p3), sizeof(Person));
// 关闭文件流
outfile.close();
}
void readFile(){
// 创建输入文件流对象
ifstream infile ("person.txt",ios::binary);
if(!infile){
cout<<"文件打开失败!"<<endl;
return ;
}
Person p1,p2,p3;
// 从文件读取学生对象
infile.read(reinterpret_cast<char*>(&p1), sizeof(Person));
infile.read(reinterpret_cast<char*>(&p2), sizeof(Person));
infile.read(reinterpret_cast<char*>(&p3), sizeof(Person));
// 关闭文件流
infile.close();
// 调用三个对象的say方法,输出从文件读取的对象的信息
p1.say();
p2.say();
p3.say();
}
int main(void){
// 测试
createFile();
readFile();
return 0;
}
作为资深的IT专家,我可以给出以下解决方案:
问题描述:
定义函数createFile创建一个文本文件person.txt,将n个Person对象写入文件,再定义函数readFile将文件中的信息读出显示在屏幕上。
解决方案:
std::string createFile(const std::string& filename) {
std::string str = filename;
std::ofstream f(str.c_str());
return f;
}
std::string filename = "person.txt";
std::ofstream file(filename.c_str());
int main() {
std::string filename = "person.txt";
int n = 5;
std::ofstream file(filename.c_str());
std::cout << "Enter number of people: ";
std::cin >> n;
std::ofstream outfile(filename.c_str());
for (int i = 0; i < n; i++) {
Person p;
std::cout << "Enter name: ";
std::cin >> p.name;
std::cout << "Enter age: ";
std::cin >> p.age;
std::cout << "Enter gender: ";
std::cin >> p.gender;
file << p.name << " " << p.age << " " << p.gender << std::endl;
}
std::cout << std::endl;
return 0;
}
int main() {
std::string filename = "person.txt";
std::ofstream file(filename.c_str());
std::string content;
std::cout << "Enter content of the file: ";
std::cin >> content;
file << content;
std::cout << std::endl;
std::cout << "The file contains " << n << " people with " << (n + 1) << " named individuals and " << (n + 2) << " genders. ";
std::cout << std::endl;
return 0;
}
以上代码中,createFile函数用于创建文本文件,readFile函数用于读取文件中的信息,其中n变量用于控制写入文件的人数。
希望这可以帮助您解决问题!