以下代码行旨在将输入文本文件中的每个单词(用新行分隔的单词)放入一个字符串矢量中,然后将每个单词从里面翻出来,并查看是否包含该单词在输入文件中的单词列表中。为什么使用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