该程序以字符串(学生姓名)为输入,根据文件中已经存在的学生人数生成该学生的卷号。然后将此信息作为结构存储在该文件中。进一步的细节在注释中。这段代码可以正常工作,直到我更改其中任何一个->
#include<iostream>
#include<string>
#include<fstream>
struct student
{
char RollNo[8];
std::string name;
};
class data
{
student stu;
public:
data() {}
//open a file for fstream in argument...mod = 0 for input mode...mod = 1 for output mode
void openn(int mod, std::fstream* yo_fp)
{
if (mod == 0)
{
yo_fp->open("cs.txt", std::ios::in);
}
else if (mod == 1)
{
yo_fp->open("cs.txt", std::ios::out | std::ios::app);
}
}
//generates roll number of student
//for example if data of 3 students is already present in file then roll number of new student will be cs4
void rollGen()
{
std::fstream* rg_fp = new std::fstream;
openn(0, rg_fp);
int i = 1;
data* temp = new data;
//if I allocate temp on stack...like, 'data temp;' and then in while loop replace 'temp' with '&temp'...programm is giving exception
//counting number of students whose data is already present in file
while (rg_fp->read((char*)temp, sizeof(data)))
{
i++;
}
strcpy_s(stu.RollNo, "cs");
std::string s = std::to_string(i);
strcat_s(stu.RollNo, s.c_str());
rg_fp->close();
delete rg_fp;
}
//take name string as input and call roll number generation function. hence providing data to student stu struct present in this class
void input()
{
std::cout << "Enter your name - ";
getline(std::cin, stu.name);
rollGen();
std::cout << "your RollNo is - " << stu.RollNo << std::endl;
}
//printing tha data of student stu struct present in class
void output()
{
std::cout << "roll no - " << stu.RollNo << std::endl;
std::cout << "name - " << stu.name << std::endl;
}
};
//write the data of class object into file after calling input() function
//using 'data stud' in argument instead of 'data& stud' gives exception
void write(data& stud, std::fstream* cur_fp)
{
stud.input();
stud.openn(1, cur_fp);
cur_fp->write((char*)&stud, sizeof(data));
std::cout << std::endl;
cur_fp->close();
}
//printing all elements of file one by one
//using 'data stud' in argument instead of 'data& stud' gives exception
void read(data& stud, std::fstream* cur_fp)
{
stud.openn(0, cur_fp);
std::cout << "Data in File is - " << std::endl << std::endl;;
while (cur_fp->read((char*)&stud, sizeof(data)))
{
stud.output();
std::cout << std::endl;
}
cur_fp->close();
std::cin.get();
}
int main()
{
std::fstream *fp = new std::fstream;
data stud;
write(stud, fp);
write(stud, fp);
read(stud, fp);
delete fp;
}
类data
包含一个成员字段sudent stu
,该成员字段包含一个std::string name
将内容存储在堆上的成员字段,因此,通过data
从文件中读取对象,rg_fp->read((char*)temp, sizeof(data))
您实际上会用导致所有各种未定义行为的无效指针填充字符串。请注意,像这样将其写入文件cur_fp->write((char*)&stud, sizeof(data));
也不起作用,因为未写入字符串内容。您应该实现适当的[de]序列化,一一存储每个类字段的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句