【发布时间】:2023-04-07 01:34:01
【问题描述】:
我正在尝试从项目中的文件导入数据,但找不到 EOF。首先,我使用 EOF 函数作为条件,但在阅读 this 后,我尝试更改代码,但仍然给出相同的错误。请帮帮我。 谢谢
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Rooms;
class Guest;
class MeetingRoomGuest;
Rooms* r_ptr[999];
int r_count=0;
ofstream infile("new.txt",ofstream::binary);
while(infile.read((char *)(&r_ptr[r_count]),sizeof(Rooms)))
{
r_count++;
}
infile.close();
int main ()
{
// some code here
return 0;
}
错误:
错误 C2059:语法错误:'while'
更新: 请让我知道这是否是更好的实现方式?谢谢
int main()
{
r_ptr[r_count]= new Rooms;
while(infile.read((&r_ptr[r_count]),sizeof(Rooms)))
{
r_ptr[++r_count]= new Rooms;
r_count++;
}
infile.close();
//some code here
}
我仍然收到错误,
错误:
错误 C2039: 'read' : is not a member of 'std::basic_ofstream<_elem>'
更新: 非常感谢。代码终于修好了,下面是最终实现,
int main()
{
r_ptr[r_count]= new Rooms;
while(infile.read((char *)(&r_ptr[r_count]),sizeof(Rooms)))
{
r_count++;
r_ptr[r_count]= new Rooms;
}
infile.close();
// some work
}
【问题讨论】:
-
在你解决了语法和编译问题之后,就会出现一个严重的设计问题:试图读取或写入
char[]的原始指针永远不会达到你想要的效果。阅读有关序列化的信息。 -
@aschepler,哦!抱歉,我差点忘了为他们分配内存。谢谢你:)
-
您在循环中将 r_count 递增一到多次。尝试 - r_ptr[r_count]= 新房间;这条线 r_ptr[r_count]= new Rooms;在不需要while循环之前
-
@daven11 :while() 之前的行对我来说似乎没有必要,因为我需要先分配内存才能使用它。我还发现我需要在循环中交换两个语句。
-
@JustAnotherProgrammer:你当然是对的——我的错