【发布时间】:2020-04-13 17:49:08
【问题描述】:
#include <iostream>
#include<fstream>
#include<string>
using namespace std;
class student{
private:
string name;
long int rollNo;
public:
static int noOfStudent;
void getData(){
cout<<"Enter name:";
getline(cin,name);
cout<<"Enter Roll No:";
cin>>rollNo;
}
void storeInFile(){
ofstream myfile;
myfile.open("studentDataBase.txt",ios::app|ios::binary);
if(myfile.fail())
exit(-1);
myfile.write((char*)this,sizeof(*this));
myfile.close();
}
void printData(){
ifstream myfile;
myfile.open("studentDataBase.txt",ios::binary);
if(myfile.fail())
exit(-1);
myfile.read((char *)this,sizeof(*this));
while(!myfile.eof()){
cout<<this->name<<" "<<this->rollNo<<"\n";
myfile.read((char *)this,sizeof(*this));
}
myfile.close();
}
};
int student::noOfStudent;
int main()
{
student st[100];
st[0].getData();
st[0].storeInFile();
st[0].printData();
}
这是用于在文件中存储学生姓名和卷号并从文件中读取以打印学生详细信息的代码。 但是在从文件中读取数据并打印时出现问题。当我运行这个程序时, 并输入学生的详细信息,然后调用 printData() 函数,则该程序可以完美运行。 但是当我再次运行该程序并尝试仅调用 printData() 函数时,在输出中会显示一些垃圾值。我不明白为什么会这样? (很抱歉代码太长了)
【问题讨论】:
-
您根本无法以这种方式阅读
std::string。myfile.read((char *)this,sizeof(*this));绝对是一个错误。std::string不是 POD 类型,它具有在恢复时无效的内部指针。注意 sizeof() 是一个编译时间常数。 -
问题在于
myfile.write正在写入std::string对象,而不是文本。因此,您可以将std::string对象中的所有变量和开销写入文件。此外,如果std::string包含指针,则指针不会很好地转换回来,因为操作系统可以在每次运行程序时移动您的程序及其内存分配。 -
由于文本是一个 可变长度 字段,因此您必须先写长度,然后是文本,或者写文本后跟终止字符,例如
nul,'\0'. -
我建议以文本格式写出,首先是卷号、空格、学生姓名,然后是换行符。对于这个小项目,你不需要写二进制; text 就可以了(文件不大,所以不值得节省)。
-
@AmitNandal 但是你不能在 C++ 中存储对象,一般情况下也不能。您可以存储 一些 对象(所谓的 POD 类型),但您的不是其中之一。
标签: c++ file-handling