-2

我试图读入文件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: \t\t"<< loadID << "\n";
        cout << "Room Name: \t\t"<< loadName << "\n";
        cout << "Room Exits: \t\t" << loadExits<<"\n";
    //}

 }
4

1 回答 1

2

operator>>对于 std::string (如 in 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;
}
于 2013-05-07T16:13:16.690 回答