我正在使用在线文件结构的代码。我正面临着解决能够读取我写入文件的问题的困难时期。[这是输入数据存储在文件中的方式。
如何使其可读?
代码:
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的内容。谢谢你的帮助!!
我的student
课程定义为
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();
};
答案 0 :(得分:1)
您正在将学生完全编写为二进制数据并从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个字符)。