C++ 将矢量的排序内容写入<string>文件

C++ Write sorted contents of vector<string> to file

本文关键字:lt string 文件 gt 排序 C++      更新时间:2023-10-16

当前读取一个.txt文件并分类内容。我试图让它写入文件的那些分类内容。目前,它只写一行,我该如何将其放入新文件中?太感谢了。-Kaiya

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <fstream>
using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}
int main()
{
    string line;
    ifstream myfile("weblog.txt");
    vector<string> fileLines;
    //stack overflow example
    if (!myfile) //test the file
    {
        cout << "Unable to open the file" << endl;
        return 0;
    }
    while (getline(myfile, line))
    {
        fileLines.push_back(line);
        //cout << line << 'n';
    }
    sort(fileLines.begin(), fileLines.end()); //sorting string vector
    for (string &s : fileLines)
    {
        cout << s << " ";
        ofstream newfile ("newfile.txt");
        newfile << s << " ";
    };
    return 0;
}
ofstream newfile ("newfile.txt");
for (string &s : fileLines)
{
   cout << s << " ";
   newfile << s << " ";
};

为每个循环迭代创建 newfile覆盖文件的内容,默认情况下。

在最后一个循环之前打开newfile,或在循环中以附加模式打开。

这是因为您在循环的每个迭代中创建一个新文件! ofstream newfile(" newfile.txt");应在循环之前写入。

ofstream newfile ("newfile.txt");
for (string &s : fileLines)
{
   cout << s << " ";
   newfile << s << " ";
};
ofstream newfile ("newfile.txt");
copy(fileLines.begin(), fileLines.end(), ostream_iterator<string>(newfile, " ") );

这是我的完整代码,谢谢小pei的帮助。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <fstream>
using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}
    int main()
    {
        string line;
        ifstream myfile("weblog.txt");
        vector<string> fileLines;
        if (!myfile) //test the file
        {
            cout << "Unable to open the file" << endl;
            return 0;
        }
        while (getline(myfile, line))
        {
            fileLines.push_back(line);
        }
        sort(fileLines.begin(), fileLines.end()); //sorting string vector
        ofstream newfile ("newfile.txt"); //write to new file
        for (string &s : fileLines)
        {
            cout << s << " ";
            newfile << s << " ";
        }
        return 0;
    }