【发布时间】:2013-02-16 05:12:52
【问题描述】:
下面几行代码的目的是将输入文本文件中的每个单词(单词用换行符分隔)放到一个字符串向量中,然后将每个单词翻过来,看看这个翻过来的单词是不是包含在输入文件的单词列表中。
我相信我的二分搜索功能和 wordTurn 功能可以正常工作。 我对我的代码做了几个简单的测试,我发现使用 while(!myFile.eof()) 循环两次可能是我的代码不起作用的原因。通过不工作,我的意思是我将输出文件(“pairs.txt”)作为一个空文档(它应该是成对的单词列表)。
也就是说,当我在第二个 while(!myFile.eof()) 循环体中放入一些简单的打印代码时,它没有被打印出来,由此我得出结论,这个循环没有到达。这更有可能,因为它是在我注释掉第一个 while(!myFile.eof()) 循环时打印的。我最初将第一个 while 循环放在 else 主体中,但这没有任何区别。
你认为问题是什么? 我尝试将这两个循环体组合到第二个循环中,它在输出文件中产生了一些东西,但这不是这段代码应该做的,这在逻辑上是不正确的。
任何建议都将不胜感激。
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;
}
【问题讨论】:
-
这里有一篇关于使用 seekg 倒带打开文件的 SO 帖子:stackoverflow.com/questions/5750485/…
-
它不会工作两次,因为它基本上从不工作。
-
你的
if(!myFile.is_open())不应该直接在你打开文件之后吗?你只需加载它,甚至不用担心参数的数量。好像你放错了一些代码。