C++ 我已经编写了一个程序来管理学生数据和重载运算符,但是我得到了一个无错误的():无效指针
//重载运算符您不能使用.write((char*)&obj,sizeof(obj))的C++ 我已经编写了一个程序来管理学生数据和重载运算符,但是我得到了一个无错误的():无效指针,c++,C++,//重载运算符您不能使用.write((char*)&obj,sizeof(obj))的从文件读取/写入非POD对象,如std::string 您需要按值正确读取/写入此类对象,例如: int main() { student s1(112,"abhimanyu"),s2(123,"abc"); student temp; ofstream ofileobject("abc.txt",ios:: out | ios::trunc); ofileobject<
从文件读取/写入非POD对象,如std::string代码>
您需要按值正确读取/写入此类对象,例如:
int main()
{
student s1(112,"abhimanyu"),s2(123,"abc");
student temp;
ofstream ofileobject("abc.txt",ios:: out | ios::trunc);
ofileobject<<s1<<s2;
ofileobject.close();
ifstream ifileobject("abc.txt",ios::in);
ifileobject>>temp;
cout<<temp;
ifileobject>>temp;
cout<<temp;
ifileobject.close();
}
其中+1用于写入'\0'
终止符。或者只使用重载对象
>s.RollNo>>s.Name;
返回ifs;
}
关于流与运算符,我正处于编程的早期阶段,当前在第12课,请详细说明或进行必要的更改阅读POD:您可以简单地读/写POD类型。对于所有其他类型,您应该分别读取/写入每个成员,可以使用该成员的重载
运算符,也可以使用其他方法。
ifstream& operator>>(ifstream &ifs, student &s)
{
file stream object
ifs.read((char*) &s,sizeof(s));
return ifs;
}
ofstream& operator<<(ofstream & ofs, student &s)
{
ofs.write((char*) &s,sizeof(s));
return ofs;
}
ostream& operator<<(ostream & os, student &s)
{
object and student object
os<<"Roll No. = "<<s.RollNo<<endl;
os<<"Name = "<<s.Name<<endl;
return os;
}
istream& operator>>(istream & is, student &s)
{
inputstream object
cout<<"Enter R0ll No.: ";
is>>s.RollNo;
cout<<"Enter Name: ";
is>>s.Name;
return is;
}
int main()
{
student s1(112,"abhimanyu"),s2(123,"abc");
student temp;
ofstream ofileobject("abc.txt",ios:: out | ios::trunc);
ofileobject<<s1<<s2;
ofileobject.close();
ifstream ifileobject("abc.txt",ios::in);
ifileobject>>temp;
cout<<temp;
ifileobject>>temp;
cout<<temp;
ifileobject.close();
}
of.write(str.data(), str.length() + 1);
of << str;
ifstream& operator>>(ifstream &ifs, student &s)
{
ifs >> s.RollNo >> s.Name;
return ifs;
}
ofstream& operator<<(ofstream & ofs, student &s)
{
ofs << s.RollNo << s.Name;
return ofs;
}