Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么这个单词排序程序只循环一次?_C++_File_Dictionary - Fatal编程技术网

C++ 为什么这个单词排序程序只循环一次?

C++ 为什么这个单词排序程序只循环一次?,c++,file,dictionary,C++,File,Dictionary,我正在尝试创建一个单词排序程序,该程序将读取.txt文件中的单词,然后将它们按从最短单词到最长单词的顺序写入新文件。因此,例如,如果第一个文件包含: 象 狗 老鼠 程序执行后,我希望第二个文件(最初为空)包含: 狗 老鼠 象 代码如下: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string word;

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

老鼠

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

老鼠

代码如下:

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
字符串字;
ifstreamreadfrom;
流式写入;
readFrom.open(“C:\\Users\\owner\\Desktop\\wordlist.txt”);
writeTo.open(“C:\\Users\\owner\\Desktop\\newwordlist.txt”);
如果(从读取和写入)
{
cout>word)
{
if(word.length()==lettercount)
{ 

cout搜索后,清除EOF标志

 readFrom.clear();
while循环将继续,直到在readFrom上设置了特殊标志,即EOF标志。开始搜索不会清除任何标志,包括EOF。在搜索之前添加以下行以清除标志,代码应该可以正常工作

readFrom.clear();

您是否尝试在调试器中运行此操作?稍后(从>>word读取)循环您正在将位置重置为0,因此它从一开始就重新开始。因此,这不是对单词的正确排序,它实际上是基于字母数的稳定排序。相同长度的单词将保留其原始相对位置,从而导致未排序的结果。这很容易修复了它!非常感谢!
readFrom.clear();