我想用VS 2022想试一试流类的read()函数,结果出现十分奇怪的乱码
这是Student类

这是main函数

这是文本文件

这是结果

为什么结果这么怪?求佬解答
我想用VS 2022想试一试流类的read()函数,结果出现十分奇怪的乱码
这是Student类

这是main函数

这是文本文件

这是结果

为什么结果这么怪?求佬解答
read()方法读取文件的内容,应该是需要write()方法写入的二进制文件,直接读取文本模式的文件,应该是会出错的。
修改如下:
参考链接:
https://c.biancheng.net/view/7603.html
https://blog.csdn.net/alal001/article/details/130836243
https://blog.csdn.net/seadplus/article/details/7802346
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
class Student{
public:
void setStu(int,char *,float);
float getScore();
void print();
private:
int id;
char name[30];
float score;
};
void Student::setStu(int d,char *n,float s){
id=d;
strcpy(name,n);
score=s;
}
float Student::getScore(){
return score;
}
void Student::print(){
cout<<id<<' '<<name<<' '<<score<<endl;
}
int main(void){
Student stu[10];
Student s1;
int id;
char name[30];
float score;
// https://c.biancheng.net/view/7603.html
// https://blog.csdn.net/alal001/article/details/130836243
int i;
fstream of("my_test2.txt",ios::out|ios::binary);
// 先使用write()方法向文件写入二进制信息
for(i=0;i<10;i++){
cout<<"请输入第"<<i+1<<"个学生的学号,姓名,成绩:"<<endl;
cin>>id>>name>>score;
s1.setStu(id,name,score);
of.write((char*)&s1,sizeof(s1));
}
of.close();
// https://blog.csdn.net/seadplus/article/details/7802346
fstream fff("my_test2.txt",ios::in|ios::binary);
if(fff.fail()){
cerr<<"文件打开错误!!!\n";
return 1;
}
// 用read()方法读取二进制文本信息
while(fff.read((char*)&s1,sizeof(s1))){
s1.print();
}
//fff.read((char*)&stu,sizeof(stu));
//stu[3].print();
fff.close();
return 0;
}
