【问题标题】:Using EOF Function as a Condition使用 EOF 函数作为条件
【发布时间】: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:你当然是对的——我的错

标签: c++ file eof


【解决方案1】:

你不能在 main 外面有一段时间

int main ()
{
    ofstream infile("new.txt",ofstream::binary);
    while(infile.read((char *)(&r_ptr[r_count]),sizeof(Rooms)))
    {   
        r_count++;
    }
    infile.close(); 

    // some code here
    return 0;
}

【讨论】:

  • 谢谢。你的回答很有帮助。
【解决方案2】:

看来你有一两个语法问题:

  1. 您的代码位于函数或 main(while 和 infile 命令)之外,需要将它们放入 main 或函数中。

  2. 你的第二个虽然需要dodo{....}while(1),但它会永远运行

  3. 所有变量都在main 之外定义。这使得它们成为全局变量,这是一件要尽可能避免的事情。它们也应该移到main

  4. ofstream 用于输出到文件,您希望ifstream 从文件中获取输入

【讨论】:

  • 谢谢。但是我仍然收到错误,如何将双指针转换为 char 指针?:'std::basic_istream<_elem>::read':无法将参数 1 从 'Rooms **' 转换为 '字符 *'
  • 这是因为(char *)(&amp;r_ptr[r_count]) 告诉程序将 r_ptr (a room*) 更改为 char* 并且它不知道该怎么做。直接从文件读取和写入类通常是个坏主意。如果您真的必须这样做,那么@aschepler 是对的 - 谷歌序列化
猜你喜欢
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
相关资源
最近更新 更多