如果沒有提供文件名,我想使用默認值。或者,如果提供文件名但文件無法訪問,請使用默認值。當我的變量肯定被使用時未使用的變量錯誤
int main(int argc, char * argv[]) {
// default settings
bool flag = false;
string fileName = "defaultMap.txt";
ifstream *infile = new ifstream(fileName);
if (argc > 1) {
fileName = argv[i]; // otherwise, it is a file name
flag = true;
delete infile;
ifstream *infile = new ifstream(fileName);
//if file is not valid:
if (!infile->good() || infile->fail()) {
cout << "Problem loading board from map file \'" << fileName << "\'." << endl;
delete infile;
flag = false;
}
}
if (!flag) ifstream *infile = new ifstream("defaultMap.txt"); //change back to default
Board * grid = new Board(*infile, playerRace, flag);
// MORE STUFF FOR MAIN HERE
}
然後,我將文件發送到一個函數中,逐字符地讀取它以填充矩陣。 Board()僅被調用一次,而boardInit在每次玩家進入新房間時被調用,並且需要從文件中讀取更多信息。
Board::Board(ifstream & fileName, string race, bool flag) {
player = new Player(race);
boardInit(fileName, race, flag);
}
void Board::boardInit(ifstream & fileName, string race, bool flag) {
char cell;
game = new Cell*[maxRow];
for (int row = 0; row < maxRow; row++) {
game[row] = new Cell[maxCol];
for (int col = 0; col < maxCol; col++) {
fileName.get(cell);
}
}
// MORE STUFF FOR boardINIT here
}
當我嘗試編譯我的錯誤
main.cc:122:23: error: unused variable 'infile' [-Werror,-Wunused-variable]
if (!flag) ifstream *infile = new ifstream("defaultMap.txt"); //change back to default
^
1 error generated.
即使我把它傳遞給板右下方(Board * grid = new Board(*infile, playerRace, flag);
)
嘗試更改'ifstream * infile = ...'到'infile = ...' – anukul
首先,停止使用'new',除非您有充足的理由,而您的代碼中沒有這個理由。其次,C++具有嵌套作用域,變量名只能在其範圍內唯一。想象一下,如果條件仍然不明確,那麼可以使用大括號。最後,你的問題是無關緊要的,因爲你沒有把它減少到顯示問題的代碼量越來越少。這可能會給你自己正確的想法而沒有問。 –
@momo爲什麼不把它變成答案,解釋發生了什麼? – juanchopanza