嘗試過了幾個小時之後,爲什麼我的C++代碼不能正常工作的要求,我發現了錯誤應在該部分的代碼中隱藏了:字符串流不讀通緝
void loadWorld(GameOfLife& game, int rij, int kolom, string fileName){
// Reads a .LIF-file and configures the GameOfLife object based on this info
ifstream ifs(fileName.c_str());
stringstream ls;
if(!ifs) throw new fileNotFound;
string line;
char tempChar;
Block tempBlock;
vector<Cel> tempVector(0);
string rule;
while(ifs.good()){
getline(ifs, line); //get next line from the file
ls.str(line); //put it into a stringstream
if(line!="") { //skip empty strings
ls >> tempChar;
if(tempChar=='#')
ls >> tempChar; //go to the next sign
switch(tempChar){
case 'N':
rule = "23/3"; //default rule
break;
case 'R':
ls >> rule; //set new rule
break;
case 'P' :
if(tempBlock.cellen.size()>0)
loadBlock(game, rij, kolom, tempBlock); //load previous block
//new block
tempBlock.cellen.clear();
ls >> tempBlock.x >> tempBlock.y;
break;
case '.' : case '*' :
cout << tempChar; //for testing
tempVector.clear();
if(tempChar=='.')
tempVector.push_back(Cel(0, fl_rgb_color(0,0,0)));
else
tempVector.push_back(Cel(1, fl_rgb_color(0,0,0)));
while(ls.good()){
ls >> tempChar;
cout << tempChar; //test
if(tempChar=='.')
tempVector.push_back(Cel(0, fl_rgb_color(0,0,0)));
else
tempVector.push_back(Cel(1, fl_rgb_color(0,0,0)));
}
tempBlock.cellen.push_back(tempVector);
cout << endl; //test
break;
default:
break;
}
}
}
loadBlock(game, rij, kolom, tempBlock); //load last block
int survival=0;
int birth=0;
extractRule(rule, survival, birth);
game.setSurvival(survival);
game.setBirth(birth);
}
該代碼是康威生命遊戲實施的一部分,應該讀取包含某個配置信息的文件,然後配置GameOfLife類型的對象'遊戲'以包含此配置。應該讀取文件的一個例子是:
#Life 1.05
#D Acorn
#D The most vigorously growing 7-cell
#D "methuselah" pattern. See also RABBITS.
#N
#P -3 -1
.*
...*
**..***
程序應該忽略前四個規則,在閱讀第五規則,應遊戲的規則設置爲23/3,正常的規則。它做到了這一切。 它還應該讀取#P之後的代碼塊。出於某種原因,它並不這樣做。正如你所看到的,我使用cout作爲代碼中不能按預期工作的部分的調試工具。我的預期產出將是:
.*
...*
**..***
卻是:
.**
*
*
我不知道爲什麼是這樣的情況。如果您有關於如何查找錯誤的任何提示,請告訴我。如果你需要更多的信息(比如Cel的Block),請告訴我。我沒有包括那些,因爲我懷疑他們會分散這個問題;即使排除使用Block或Cel的零件,它也會持續存在。
注:必要的包括已經完成,程序在Eclipse中編譯沒有任何錯誤或警告。
你的英語比大多數母語人士好幾個數量級。不幸的是,你的代碼...:p –
我不明白,爲什麼你認爲它的'stringstream'相關,而不是你的實現的錯誤邏輯?我沒有閱讀代碼,但是你確定遊戲在錯誤模式下工作嗎?你不顯示,你讀的是什麼。此外,Hi's和Bye's也不需要這裏。只有問題很重要=) – luk32