新手,我的代码似乎不是用vscode编译的.它在使用dev c++时提供了所需的输出.它给我错误,而从文件读取,写入文件没有问题.我在代码下面发布了错误消息.
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
class student{
private:
char name[25];
int id;
int age;
public:
void get(){
cin>>name>>id>>age;
}
void show(){
cout<<name<<id<<age;
}
void write2file(){
ofstream outfile("student.dat",ios::binary|ios::app);
get();
outfile.write(reinterpret_cast<char*>(this),sizeof(*this));
}
void readfromfile(){
ifstream infile("student.dat",ios::binary|ios::in);
while(!infile.eof()){
if(infile.read(reinterpret_cast<char*>(this),sizeof(*this))>0){
show();
}
}
}
};
int main(){
student s;
s.write2file();
s.readfromfile();
return 0;
}
这是我在VS代码中运行程序时遇到的错误,但同一个程序在dev c++中运行得很好.
awd.cpp: In member function 'void student::readfromfile()':
awd.cpp:26:76: error: no match for 'operator>' (operand types are 'std::basic_istream<char>::__istream_type' {aka 'std::basic_istream<char>'} and 'int')
26 | if(infile.read(reinterpret_cast<char*>(this),sizeof(*this))>0){
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
| | |
| | int
| std::basic_istream<char>::__istream_type {aka std::basic_istream<char>}
awd.cpp:26:76: note: candidate: 'operator>(int, int)' (built-in)
26 | if(infile.read(reinterpret_cast<char*>(this),sizeof(*this))>0){
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
awd.cpp:26:76: note: no known conversion for argument 1 from 'std::basic_istream<char>::__istream_type' {aka 'std::basic_istream<char>'} to 'int'
In file included from C:/msys64/mingw64/include/c++/12.1.0/string:47,
from C:/msys64/mingw64/include/c++/12.1.0/bits/locale_classes.h:40,
from C:/msys64/mingw64/include/c++/12.1.0/bits/ios_base.h:41,
from C:/msys64/mingw64/include/c++/12.1.0/ios:42,
from C:/msys64/mingw64/include/c++/12.1.0/ostream:38,
from C:/msys64/mingw64/include/c++/12.1.0/iostream:39,
from awd.cpp:1:
更好的代码应该是这样
正如已经指出的那样,`istream::read 8215e不返回整数,这是原始代码似乎假设的.
相反,与大多数I/O函数一样,流本身是返回的.在布尔上下文中,这可以用来查看流是否处于良好状态.如果不是,则之前的输入/输出操作失败.