【问题标题】:reading/writing class objects to files in c++将类对象读/写到c ++中的文件
【发布时间】:2014-09-08 15:29:22
【问题描述】:
#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

class Student{
private:
    char name[40];
    char grade;
    float marks;
public:
    void getdata();
    void display();
};

void Student::getdata(){
    char ch;
    cin.get(ch);
    cout<<"Enter name : ";
    cin.getline(name,40);
    cout<<"Enter grade : ";
    cin>>grade;
    cout<<"Enter marks : ";
    cin>>marks;
    cout<<"\n";
}

void Student::display(){
    cout<<"Name : "<<name<<"\t";
    cout<<"Grade : "<<grade<<"\t";
    cout<<"Marks : "<<marks<<"\t"<<"\n";
}

int main(){
    system("cls");
    Student arts[3];
    fstream f;
    f.open("stu.txt",ios::in|ios::out|ios::binary);
    if(!f){
        cerr<<"Cannot open file !";
        return 1;
    }
    for(int i=0;i<3;i++){
        arts[i].getdata();
        f.write((char*)&arts[i],sizeof(arts[i]));
    }
    f.seekg(0); //The question is about this statement;
    cout<<"The contents of stu.txt are shown below : \n";
    for(int j=0;j<3;j++){
        f.read((char*)&arts[j],sizeof(arts[j]));
        arts[j].display();
    }
    f.close();
    return 0;
}

上述程序从“stu.txt”文件中读取和写入Student对象。 它运行良好。但即使我关闭 fin.seekg(0) 语句,它也运行良好。我不明白这部分?我们是否不应该将文件指针设置为文件的开头 - 在开始从文件中读取对象之前(在这个特定程序的上下文中)?

【问题讨论】:

  • 不,它不能正常工作,只是你在阅读时没有检查错误。
  • @Galik 只有一个文件指针:stackoverflow.com/questions/15670359/…
  • 尝试创建一个新数组来读取,看看它是否仍然有效。
  • @CashCow 谢谢!现在很清楚了!

标签: c++ class object c++11 file-io


【解决方案1】:

如果您在文件末尾,read 方法调用将失败,因此 Student 结构保持不变(因此您只是再次打印在将它们写入文件后保持不变的相同结构)。

【讨论】:

  • 谢谢,我现在明白了 - 我创建了一个新的对象数组并试图关闭 fin.seekg(0) - 它确实打印了所有垃圾!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多