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



我有一个函数,我想获取一个文件,查看文件中的单词,按字母顺序排列,然后用它替换文件。到目前为止,我已经掌握了按字母顺序排列单词的方法。问题是,它只将最后一个单词保存到文件中。这是我当前的代码:

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)中的主要问题。

不过,对于记录,我想建议您使用powerfull ostream_iterator进行更高效的输出:它避免了多次打开/关闭输出文件,并且不需要在所有字符串中使用尾随空格。话虽如此,我建议也取消不必要的双重通过阅读:

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, " "));
} 

最新更新