为什么在尝试使用 C++ 从文本文件中读取结构时,我会得到一个带有值的额外行?

问题描述 投票:0回答:0

我正在使用 C++,通过创建一个分别具有 name 和 age ie.string 和 int 数据成员的结构,并将结构的值存储在文本文件中,然后再次从文件中读取并将内容存储在新结构中以进行打印它,但我得到了一条带有价值的额外线。

我试着去解决一个类似的问题,但不能很好地理解它

#include<bits/stdc++.h>
using namespace std;

struct student {
    string name;
    int age;
};
int main() {
    student s1;
    s1.age=10;
    s1.name="saurav";
    ofstream out;
    out.open("structout.txt",ios::app);
    out.write((char*)&s1,sizeof(s1));
    out.close();
    ifstream in;
    in.open("structout.txt");
    while(in.eof()==0) {
        student s2;
        in.read((char*)&s2, sizeof(s2));
        cout<<s2.name<<" "<<s2.age<<endl;
    }
    in.close();
}

输出应该是 索拉夫 10

但是当前输出是 索拉夫 10 10

c++ structure file-handling ifstream ofstream
© www.soinside.com 2019 - 2024. All rights reserved.