以下代碼行旨在將輸入文本文件中的每個單詞(用新行分隔的單詞)放入一個字符串矢量中,然後將每個單詞從裏面翻出來,並查看是否包含該單詞在輸入文件中的單詞列表中。爲什麼使用while(!input.eof())循環兩次不起作用?
我相信我的二進制搜索功能和wordTurn功能正常工作。 我對我的代碼做了幾個簡單的測試,並且發現使用while(!myFile.eof())循環兩次可能導致我的代碼無法正常工作。通過不工作,我的意思是我得到輸出文件(「pairs.txt」)作爲一個空文件(它應該是一對單詞列表)。當我在第二個while(!myFile.eof())循環體中放置一些簡單的打印代碼時,它沒有打印出來,從中我得出這個循環沒有達到。這更有可能,因爲它在我第一次註釋掉(!myFile.eof())循環時打印出來。我最初把第一個while循環放在else的body處,但這沒有什麼區別。
您認爲是什麼問題? 我嘗試將這兩個循環體合併到第二個循環中,並且它在輸出文件中生成了一些內容,但這不是代碼應該執行的操作,而且這在邏輯上不正確。
任何建議的話將不勝感激。
int main(int argc, char* argv[]) {
vector<string> words;
ifstream myFile(argv[1]);
ofstream outputFile("pairs.txt");
string vocab;
string s;
int count;
while(!myFile.eof()) { //first while(!myFile.eof()) loop
getline(myFile, s);
words.push_back(s);
}
if(argc != 2) {
cout << "Usage: provide the name of one input file after the dictlookupHN executable file." << endl;
return (1);
}
else {
if(!myFile.is_open()) {
cerr << "Error: unable to open file " << argv[1] << endl;
return (1);
}
else {
while(!myFile.eof()) { //second while(!myFile.eof()) loop
getline(myFile, vocab);
string turnedWord = wordTurn(vocab);
if(binsearch(words, turnedWord) != "") {
outputFile << vocab << ":" << turnedWord << endl;
count++;
}
}
}
}
myFile.close();
outputFile.close();
return 0;
}
有一個SO張貼瞭解使用seekg倒帶打開的文件:http://stackoverflow.com/questions/5750485/ifstream-equivalent-of-file-s-rewind-method – 2013-03-01 16:27:22
它不工作兩次,因爲它基本上*從來沒有工作。* – 2013-03-01 16:29:25
不應該你打開文件後,你的'if(!myFile.is_open())'?你只需加載它,而不必擔心參數的數量。好像你錯放了一些代碼。 – GManNickG 2013-03-01 16:41:11