完成调用功能后,infile中的位置发生变化

时间:2016-11-01 20:31:02

标签: c++ debugging

当我在文件中读取退出时,出于某种原因它跳过与num_rooms完全相同的数量

调用函数read_exits后位置发生变化。在调用read_rooms之后,该位置是129,但是当它进入read_exits时,它是189

const int MAX_ROOMS = 50;
const int MAX_EXITS = MAX_ROOMS * 4    
std::ifstream input;
int read_world(std::ifstream &input, std::string rooms[MAX_ROOMS], int &num_rooms, bool exits[MAX_EXITS],
              int &num_exits);
int read_rooms(std::ifstream &input, std::string rooms[MAX_ROOMS], int &num_rooms);
int read_exits(std::ifstream &input, bool exits[], int &num_exits);

int main() {
     char fileName[26];
     std::cout<<"filename::";
     std::cin.getline(fileName, 26);
     input.open(fileName, std::ios::in);
     std::string rooms[MAX_ROOMS];
     int num_rooms;
     bool exits[MAX_EXITS];
     int num_exits;
     read_world(input,rooms,num_rooms,exits,num_exits);
     input.close();
     return 0;
 };
 int read_world(std::ifstream &input, std::string rooms[MAX_ROOMS], int &num_rooms, bool exits[MAX_EXITS],
                int &num_exits) {
      std::string fnCaller;
      while (!input.eof()) {
          getline(input, fnCaller, ' ');// to check which function to call
          if (fnCaller == "rooms") {
              std::string temp;
              getline(input, temp);
              num_rooms = atoi(temp.c_str());
              read_rooms(input, rooms, num_rooms);
              int length = input.tellg();
              std::cout<<length;//129
           }
           getline(input, fnCaller, ' ');
           if (fnCaller == "exits") {
              std::string temp;
              getline(input, temp, ' ');
              num_exits = atoi(temp.c_str());
              read_exits(input, exits, num_exits);
           }
       }
   };

  int read_rooms(std::ifstream &input, std::string rooms[MAX_ROOMS], int &num_rooms) {
      for (int i = 0; i < num_rooms; i++) {//get the info
          std::string str;
          getline(input, str, '\n');
          rooms[i] = str;
       }
       return 0;
   };

 int read_exits(std::ifstream &input, bool exits[], int &num_exits) {
      int length = input.tellg();//189
      std::cout<<length;
      for (int i = 0; i < num_exits; i++) {//get the info
           std::string str;
           getline(input, str);
           std::cout<<str<<std::endl;
           if (str == "locked") {
             exits[i] = true;
           } else if (str == "unlocked") {
               exits[i] = false;
           }
       }
       return 0;
   };

这是我的文件内容

rooms 7 

front of the house

living room

guest bedroom

closet

hallway

master bedroom

garden

exits 6

locked

locked

unlocked

unlocked

locked

locked

1 个答案:

答案 0 :(得分:0)

你不应该这样做:

getline(input, fnCaller, ' ');

两次。第一次执行此操作时,您会将类型读入fnCaller,因此它包含roomsexits。如果它包含rooms,则第一个if块执行并读取房间数据。

但如果它包含exits,您想要执行第二个if块。但是,您首先再次调用getline,它会读取当前行的下一个字。

摆脱第二条getline(input, fnCaller, ' ');行。使用else if代替另一个if,因为这两种情况是互斥的。