我的字母字符串管理器无法正确保存到文件中

My alphabetical string organizer won't save into a file correctly

我有一个功能,我想获取一个文件,查看文件中的单词,将它们按字母顺序排列并用它替换文件。到目前为止,我已经可以按字母顺序获取单词。问题是,它只将最后一个词保存到文件中。 这是我当前的代码:

void thingy(string Item)
{
        fstream File;  // Open the file, save the sorted words in it, and then close it.
        File.open("Data/Alphabet.txt", ios::out | ios::in);
        File << Item;
        File.close();
}




void Alphabetical_Order(string Text_File)
{

fstream file;      
file.open(Text_File);         // Open the file that we are going to organize
std::set<std::string> sortedItems;  // The variable that we will store the sorted words in


fstream words;            // To see how many words are in the file
words.open(Text_File);
int Words = 0;
do
{
    string word;
    words >> word;
    Words++;
} while (!words.eof());




for (int i = 1; i <= Words; ++i)  // Set a loop to take the words out of the file and put them in our variable
{
    std::string Data;
    file >> Data;
    Data = Data + " ";
    sortedItems.insert(Data);
}





std::for_each(sortedItems.begin(), sortedItems.end(), thingy);
}

有人知道如何解决这个问题吗?

当您在 thingy 中打开 fstream 时,也尝试使用 ios::ate 标志打开。这将允许您将文本附加到文件,而不是每次调用该函数时都重写。

也就是说,您不应该在每次调用函数时都打开和关闭文件。也许传递对从函数 thingy.

外部管理的 fstream 的引用

希望对您有所帮助。

Aiden 已经指出了您代码中的主要问题 (+1)。

作为记录,我想向您推荐一个使用强大 ostream_iterator 的更高效的输出:它避免了 opening/closing 输出文件很多次并且不需要尾随所有字符串中的空格。话虽这么说,我建议也取消不必要的双遍阅读:

void Alphabetical_Order(string Text_File)
{
    ifstream file(Text_File);    // Open in read mode   
    std::string word;
    std::set<std::string> sortedItems;  // The variable that we will store the sorted words in

    while (file >> word) {       // just read the file in one pass 
        sortedItems.insert(word);    // to populate the set
    }

    ofstream ofs("alphasorted.txt");                                  
    std::copy(sortedItems.begin(), sortedItems.end(), std::ostream_iterator<std::string>(ofs, " "));
}