Infile不读取文件内容
infile does not read file contents
我试图读取文件Rooms.txt:
Room ID: 1.
Room Name: Beach East.
Room Exits: 2, 3.
Room ID: 2.
Room Name: Beach West.
Room Exits: 1.
Room ID: 3.
Room Name: Forest.
Room Exits: 1,4.
Room ID: 4.
Room Name: Cave.
Room Exits: 3.
但是我没有得到正确的输入。房间名是-8987678678。我不明白为什么我会收到垃圾……这是我写的读取文本文件的函数,有没有人看到问题:
void Rooms :: loadRooms()
{
string fileName = "Rooms\Rooms.txt";
ifstream infile(fileName);
string garbage;
int loadID;
string loadName;
string loadExits;
//while( )
//{
infile >>garbage;
infile >>loadID ;
infile >>garbage;
infile >>garbage;
infile >> loadName;
infile >> garbage;
infile >>garbage;
infile >>loadExits;
infile >>garbage;
cout << "Room ID: tt"<< loadID << "n";
cout << "Room Name: tt"<< loadName << "n";
cout << "Room Exits: tt" << loadExits<<"n";
//}
}
operator>>
对于std::string(如infile >> garbage;
)读取单个空格分隔的单词,因此您的第一个infile >> garbage;
从输入读取(并某种程度上丢弃)Room
。然后infile >> LoadId
尝试从输入中读取ID:
并将其放入LoadId
。因为ID:
不是整数,所以转换失败。
设置流的fail
位,以便所有进一步尝试从流中读取的操作立即失败。
您可能想要编写一个小例程来读取(并可能验证)标签和与该标签关联的值,然后使用它来读取数据,因此代码看起来像:
loadID = getvalue(infile, "Room ID");
loadName = getvalue(infile, "Room Name");
loadExits = getvalue(infile, "Room Exits");
在本例中,getvalue
类似于:
std::string getvalue(std::istream &infile, std::string const &label) {
std::string input_label;
std::getline(infile, input_label, ':');
if (input_label != label) {
// handle the error -- the label in file didn't match what we expected
}
std::string ret;
std::getline(infile, ret);
return ret;
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量