本文介绍了为什么这个单词排序程序只循环一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个单词排序程序,它将读取.txt文件中的单词,然后按照从最短单词到最长单词的顺序将其写入新文件。例如,如果第一个文件包含:

I'm trying to create a word sorting program that will read the words in a .txt file and then write them to a new file in order from shortest words to longest words. So, for instance, if the first file contains:

大象

鼠标

程序执行后,我想要第二个文件(最初为空)包含:

Once the program has executed, I want the second file (which is initially blank) to contain:

鼠标

大象

这里是代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    string word;
    ifstream readFrom;
    ofstream writeTo;
    readFrom.open("C:\\Users\\owner\\Desktop\\wordlist.txt");
    writeTo.open("C:\\Users\\owner\\Desktop\\newwordlist.txt");
    if (readFrom && writeTo)
    {
        cout << "Both files opened successfully.";
        for (int lettercount = 1; lettercount < 20; lettercount++)
        {
            while (readFrom >> word)
            {
                if (word.length() == lettercount)
                    {
                        cout << "Writing " << word << " to file\n";
                        writeTo << word << endl;
                    }
            }
            readFrom.seekg(0, ios::beg); //resets read pos to beginning of file
        }
    }
    else
        cout << "Could not open one or both of files.";

    return 0;
}

对于for循环的第一次迭代,嵌套while循环似乎工作就好了,将正确的值写入第二个文件。但是,在for循环的所有下一次迭代中出现问题,因为没有更多的单词写入文件。为什么呢?

For the first iteration of the for loop, the nested while loop seems to work just fine, writing the correct values to the second file. However, something goes wrong in all the next iterations of the for loop, because no further words are written to the file. Why is that?

非常感谢。

推荐答案

while (readFrom >> word)
{

}
readFrom.seekg(0, ios::beg); //resets read pos to begin

while循环将继续,直到在readFrom上设置特殊标志,即,EOF标志。寻找开始清除任何标志,包括EOF。在之前添加以下行以清除标记,代码应该正常工作。

The while loop will continue until special flags are set on readFrom, namely, the EOF flag. Seeking to the beginning does not clear any flags, including EOF. Add the following line right before the seek to clear the flags and your code should work fine.

readFrom.clear();

这篇关于为什么这个单词排序程序只循环一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:22