C++ 我的按字母顺序排列的字符串管理器赢了';不能正确地保存到文件中
我有一个函数,我想获取一个文件,查看文件中的单词,按字母顺序排列,然后用它替换文件。到目前为止,我已经把单词按字母顺序排列好了。问题是,它只将最后一个单词保存到文件中。 这是我目前的代码:C++ 我的按字母顺序排列的字符串管理器赢了';不能正确地保存到文件中,c++,fstream,C++,Fstream,我有一个函数,我想获取一个文件,查看文件中的单词,按字母顺序排列,然后用它替换文件。到目前为止,我已经把单词按字母顺序排列好了。问题是,它只将最后一个单词保存到文件中。 这是我目前的代码: void thingy(string Item) { fstream File; // Open the file, save the sorted words in it, and then close it. File.open("Data/Alphabet.txt",
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);
}
void thingy(字符串项)
{
fstream File;//打开文件,保存排序后的单词,然后关闭。
打开(“Data/Alphabet.txt”,ios::out | ios::in);
文件>word;
Words++;
}而(!words.eof());
对于(int i=1;i>数据;
数据=数据+“”;
插入(数据);
}
std::for_each(sortedItems.begin()、sortedItems.end()、thingy);
}
有人知道如何解决这个问题吗?当您在
thingy
中打开fstream
时,也可以尝试使用ios::ate
标志打开。这将允许您将文本附加到文件中,而不是每次调用函数时都重写
也就是说,您不应该每次调用函数时都打开和关闭文件。可以将引用传递给从函数外部管理的fstream
我希望这会有所帮助。艾登已经指出了代码(+1)中的主要问题 但是,对于记录,我建议您使用powerfull实现更高效的输出:它避免了多次打开/关闭输出文件,并且不需要在所有字符串中使用尾随空格。尽管如此,我还是建议取消不必要的双过程读取:
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, " "));
}
void字母顺序(字符串文本文件)
{
ifstream文件(Text_文件);//以读取模式打开
字符串字;
std::set sortedItems;//我们将在其中存储已排序单词的变量
而(file>>word){//只需一次读取文件即可
sortedItems.insert(word);//填充集合
}
ofs流(“alphasorted.txt”);
std::copy(sortedItems.begin()、sortedItems.end()、std::ostream_迭代器(ofs,”);
}
只需对函数thingy
传递注释。fstream
构造函数可以打开文件,而不需要单独调用open
。执行此操作时,默认模式为ios::out | ios::in
。析构函数将关闭文件。因此该函数只需要两行:std::fstream file(“Data/alphabet.txt”);文件,这是因为您的fstream位于文件末尾。您必须重新定位流才能再次读取它。这样可以将所有单词保存到文件中,并且它们都是按字母顺序排列的。感谢您的回复!