1
當我爲退出讀取文件中的,由於某種原因,跳過完全相同的量num_rooms當我由於某種原因,在文件中讀取它通過它改變了文件中的位置自
我知道有一個錯誤後完成的地方調用該函數read_rooms和進入而下一次迭代(input.good())
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);
}
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) {
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
你應該包括[最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)再現您的問題。你的代碼有兩個'read_world'函數,沒有一個是完整的'{'不是很好的平衡。 – Franck
我重新檢查了我的代碼並修復了一切,並且已經從我的代碼中刪除了很多東西。 –
'while(input.good())'與['while(!input.eof())']具有相同的問題(http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside- a-loop-condition-considered-wrong) – molbdnilo