【问题标题】:Reading from ifstream multiple times多次从 ifstream 中读取
【发布时间】:2013-11-27 08:21:43
【问题描述】:

如果这是一个非常简单的问题,我深表歉意,但我对 C++ 还很陌生,而且我正在处理的项目遇到问题。

该项目的一部分涉及将对象的信息写入 .txt 文件并能够读取该 .txt 文件以加载到对象中。 (在这种情况下,写入的是信息而不是对象本身,因此有人可以轻松地编辑 .txt 以更改对象)。

我调用的从 .txt 文件中读取的函数如下:

void Room::load(ifstream& inFile)
{
string garbage;
string str;
inFile >> garbage >> garbage >> mId;
inFile >> garbage; getline(inFile, mName);
inFile >> garbage; getline(inFile, mDesc);
loadVec(garbage, inFile, mExits);
}

“垃圾”用于删除 .txt 中的描述符以帮助用户。

一个典型的房间对象应该如下所示:

Room ID: 2
Name: Foyer
Description: The player can enter here from the kitchen.
Exits: 3 4 

当我尝试加载多个房间时出现问题。第一个房间将完美加载,但任何后续房间都将无法正确加载。

我至少预计它会以这样的方式失败,因为 .txt 文件中的第一个房间被重复加载,但事实并非如此。

如果有人能提供任何帮助,我将不胜感激,在此先感谢。

编辑: 现在我正在使用以下代码加载房间:

if (inFile)
    {
    //Assign data to objects
    room0.load(inFile);
    room1.load(inFile);
    }

在这种情况下,room0 以 .txt 文件中第一个房间的数据结束,但 room1 保持不变,只是出于某种原因清除了其出口。

此时测试程序给出以下结果:

BEFORE LOAD

ID= -1
NAME= Nowhere
DESC= There's nothing here.
Exits= -1

ID= -1
NAME= Nowhere
DESC= There's nothing here.
Exits= -1

AFTER LOAD

ID= 1
NAME=  Kitchen
DESC=  This is the first room the player will see.
Exits= 2 3 5 6

ID= -1
NAME= Nowhere
DESC= There's nothing here.
Exits=

Press any key to continue . . .

这些房间在加载之前和之后分别是 room0 和 room1。

下面是 loadVec 函数的样子:

//Loads consecutive integers from inFile, saving them to vec
void loadVec(string& garbage, ifstream& inFile, vector<int>& vec)
{
int num;
vec.clear();

inFile >> garbage >> num;
vec.push_back(num);

while (inFile)
{
    inFile >> num;
    vec.push_back(num);
}

vec.erase(vec.begin() + vec.size() - 1);
}

以及应该从中加载程序的未经编辑的 .txt 文件:

Room ID: 1
Name: Kitchen
Description: This is the first room the player will see.
Exits: 2 3 5 6

Room ID: 2
Name: Foyer
Description: The player can enter here from the kitchen, they can exit to the rooms     with the IDs listed as 'Exits'.
Exits: 3 4 

Room ID: 3
Name: Bathroom
Description: This is the third room.
Exits: 4 

【问题讨论】:

  • 上面的代码似乎没有加载出口。如果那不是问题,那么我认为您需要显示更多代码。特别是你需要显示 loop 你尝试加载多个房间。
  • 其他房间的信息是否也存储在加载函数中?您是否尝试在写入文件后关闭文件并再次打开以进行阅读?
  • loadVec 函数可能有问题吗?你怎么调用这个函数?您能否说明一下您如何使用它的背景信息?您是否尝试过在调试器中逐行执行代码?
  • 我在问题中添加了更多信息,我尝试在观察“垃圾”变量的同时逐步执行加载函数以查看它包含的内容,但在第一次执行后它仍然为空。
  • 您能否也请显示loadVec 功能?还有完整的(未经编辑的)输入文件?

标签: c++ load ifstream


【解决方案1】:

问题是,在您阅读出口后,流failbit 已设置。只要设置它就不会读取任何内容。

您必须致电std::istream::clear 来清除错误。


顺便说一句,还有一种更类似于 C++ 的方式来读入向量:

std::copy(std::istream_iterator<int>(inFile),
          std::istream_iterator<int>(),
          std::back_inserter(vec));

参考资料:

在执行此操作之前,您当然必须先阅读“标签”(garbage)。

【讨论】:

  • @rbissett 不客气。 :) 顺便说一句,您可能想看看我的更新,有“更好”的方式将值读入向量。
猜你喜欢
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多