C++将向量的排序内容写入文件
这当前读取一个.txt文件并对内容进行排序。我试图让它把向量的排序内容写入一个文件。目前它只写一行,我怎样才能让它把所有的行都放到新文件中呢?非常感谢你-凯亚C++将向量的排序内容写入文件,c++,string,sorting,vector,C++,String,Sorting,Vector,这当前读取一个.txt文件并对内容进行排序。我试图让它把向量的排序内容写入一个文件。目前它只写一行,我怎样才能让它把所有的行都放到新文件中呢?非常感谢你-凯亚 #include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <fstream> using namespace std;
#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 newfilenewfile.txt; 应该在循环之前写入
ofstream newfile ("newfile.txt");
for (string &s : fileLines)
{
cout << s << " ";
newfile << s << " ";
};
默认情况下,为每个循环迭代创建新文件将覆盖文件的内容
在最后一个循环之前打开新文件,或者在循环中以追加模式打开它。这是我的完整代码,谢谢裴晓天的帮助
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, " ") );
#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;
}