infile不读取文件内容

时间:2013-05-07 15:46:48

标签: c++ file-io

我试图读入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";
    //}

 }

1 个答案:

答案 0 :(得分:2)

operator>>对于std :: string(如在infile >> garbage;中)读取单个空格分隔的单词,因此您的第一个infile >> garbage;读取(以及丢弃的排序){{ 1}}来自输入。然后Room尝试从输入中读取infile >> LoadId并将其放入ID:。由于LoadId不是整数,因此转换失败。

设置流的ID:位,以便从流中读取所有进一步的尝试立即失败。

您可能希望编写一个小例程来读取(并可能验证)与该标签关联的标签和值,然后使用它来读取数据,因此代码看起来像:

fail

在这种情况下,loadID = getvalue(infile, "Room ID"); loadName = getvalue(infile, "Room Name"); loadExits = getvalue(infile, "Room Exits"); 类似于:

getvalue