gpt4 book ai didi

c++ - 不可读的文件

转载 作者:行者123 更新时间:2023-11-28 04:39:38 25 4
gpt4 key购买 nike

我在文件结构上使用在线代码。我很难解决能够读取我写入文件的内容的问题。[这就是输入的数据存储在文件中的方式。

如何让它可读?

enter image description here

代码:

void write_student() {
student st;
int nu, fla = 0;
ofstream outFile;
outFile.open("stu1.txt", ios::app);
cout << "Enter roll number";
cin >> nu;
cout << "Checking for constraint violation......";
fla = pkey(nu);
if (fla == 0) {
st.getdata();
outFile.write((char *)&st, sizeof(student));
outFile.open("stu1.txt", ios::app);
outFile.close();
cout << "\n\nStudent record Has Been Created ";
cin.ignore();
} else
cout << "\n\nPRIMARY KEY CONSTRAINT VIOLATED\n";
getch();
}
void student::getdata() {
cout << "\nConfirm The roll number of student ";
cin >> rollno;
cin.ignore();
cout << "\n\nEnter The Name of student ";
cin >> name;
cin.ignore();
cout << "\nEnter The marks in Cryptography out of 100 : ";
cin >> p_marks;
cin.ignore();
cout << "\nEnter The marks in File Structure out of 100 : ";
cin >> c_marks;
cin.ignore();
cout << "\nEnter The marks in Software Testing out of 100 : ";
cin >> m_marks;
cin.ignore();
cout << "\nEnter The marks in Operating System out of 100 : ";
cin >> e_marks;
cin.ignore();
cout << "\nEnter The marks in Python out of 100 : ";
cin >> cs_marks;
cin.ignore();
}

这是代码的一部分,其中添加了学生的分数。我希望能够读取 stu1.txt 的内容。感谢您的帮助!!

我的学生类定义为

class student 
{
int rollno;
char name[50];
int p_marks, c_marks, m_marks, e_marks, cs_marks;
float per;
char grade;
void calculate();

public:
void getdata();
void getdata1();
void showdata();
void show_tabular();
int retrollno();
};

最佳答案

您将 student 完全写成二进制数据并从 ASCII 文件中读取它。

一个简单的解决方案是在学生类中实现一个writeToFile函数:

class student 
{
int rollno;
char name[50];
int p_marks, c_marks, m_marks, e_marks, cs_marks;
float per;
char grade;
void calculate();

public:
void getdata();
void getdata1();
void showdata();

void write(std::ofstream& file); //<--- implement writing function

void show_tabular();
int retrollno();
};

void student::write(std::ofstream& file){
if(!file.is_open())
return;
file << "Name : " << std::string(name) << "\n";
file << "Roll no.: " << rollno << "\n";

file << "Marks : " << "\n";
file << "\tp: " << p_marks "\n";
file << "\tp: " << c_marks << "\n";
file << "\tp: " << m_marks << "\n";
file << "\tp: " << e_marks << "\n";
file << "\tp: " << cs_marks << "\n";

file << "Per. : " << per << "\n";
file << "Grade : " << grade<< "\n";
}

但要注意名称 char 数组。如果没有字符串终止(\0),它会在名称后写出垃圾(假设名称短于 50 个字符)。

关于c++ - 不可读的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50521142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com