Infile不读取文件内容

infile does not read file contents

本文关键字:文件 读取 Infile      更新时间:2023-10-16

我试图读取文件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;
}