简体   繁体   English

写入文件时出现c ++怪异字符

[英]c++ weird characters appear while writing to a file

When i run this code, and open the .dat file in notepad/wordpad it shows some weird characters 当我运行此代码并在记事本/写字板中打开.dat文件时,它显示了一些奇怪的字符

#include<iostream>
#include<fstream>
using namespace std;

class Student
{
    int rollno;
    char name[20];
    char div[20];
public:
    void accept()
    {
        cout<<"enter rollno"<<endl;
        cin>>rollno;
        cout<<"Enter name"<<endl;
        cin>>name;
        cout<<"Enter div"<<endl;
        cin>>div;
    }
    void write_rec()
    {
        ofstream f;
        f.open("Student.dat",ios::binary|ios::app);
        Student s;
        s.accept();
        f.write((char*)&s,sizeof(s));
        f.close();
    }
    void display()
    {
        ifstream f;
        Student s;
        f.open("Student.dat",ios::binary|ios::in);
        while(f.read((char*)&s,sizeof(s)))
            s.show();
        f.close();
    }
    void show()
    {
        cout<<rollno<<endl;
        cout<<name<<endl;
        cout<<div<<endl;
    }
};
int main()
{
    Student s;
    s.write_rec();
    s.display();

}

The code is getting compiled and run perfectly but when i open the "Student.dat" file it shows some weird characters 代码正在编译并完美运行,但是当我打开“ Student.dat”文件时,它显示了一些奇怪的字符

This line: 这行:

    f.write((char*)&s,sizeof(s));

Is writing the raw binary bytes of your Student object into the file. 正在将Student对象的原始二进制字节写入文件。 If that's not the behavior you intended, you'll need to do something else, eg translate the member fields of your Student object (in particular the rollno variable, which is an int ) into ASCII text strings and write those strings into the file instead. 如果这不是您想要的行为,则需要做其他事情,例如将Student对象的成员字段(特别是rollno变量,它是一个int )转换为ASCII文本字符串,然后将这些字符串写入文件中。 。

on both places when you open file: 在打开文件的两个地方:

    f.open("Student.dat",ios::binary|ios::app);

and: 和:

    f.open("Student.dat",ios::binary|ios::in);

you open as binary. 您以二进制打开。 try to remove this option. 尝试删除此选项。

as you can see here and here , these are platform specific behaviors. 如您在此处此处所看到的,这些是特定于平台的行为。

take a look at this example 这个例子

EDIT: 编辑:

and, of course, as Jeremy observed, you have to write meaningful text to your file. 当然,正如Jeremy所言,您必须在文件中写入有意义的文本。 on this line: 在这条线上:

    f.write((char*)&s,sizeof(s));

you are actually writing each byte (as (char*)) of your object. 您实际上是在写对象的每个字节(如(char *))。 if you understand what you're doing, and that's what you want to observe, than ok. 如果您了解自己在做什么,那就是您想要观察的事情,那就好了。 but maybe you should compare both outputs, from this method and from Jeremy's suggestion. 但是也许您应该比较此方法和杰里米(Jeremy)的建议的两种输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM