我正在尝试编写一个程序来打开一个包含此格式的名称列表的 txt 文件(忽略项目符号):
- 3分
- 4 拉尔夫
- 1 版
- 2 凯文
并会根据前面的数字创建一个带有组织名称的文件:
- 1 版
- 2 凯文
- 3分
- 4 拉尔夫
我无法将 vector 输出到新文件“outfile.txt” 在第 198 行,我收到错误消息“不匹配‘operator<<...”
我还可以使用哪些其他方法来输出 vector ?
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std;
struct info
{
int order;
string name;
};
int sortinfo(info a, info b)
{
return a.order < b.order;
}
int main()
{
ifstream in;
ofstream out;
string line;
string collection[5];
vector <string> lines;
vector <string> newLines;
in.open("infile.txt");
if (in.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}
out.open("outfile.txt");
if (out.fail())
{
cout << "Output file opening failed. \n";
exit(1);
}
vector <info> inf;
while(!in.eof())
{
info i;
in >> i.order;
getline(in, i.name);
inf.push_back(i);
}
sort(inf.begin(), inf.end(), sortinfo);
ostream_iterator <info> output_iterator(out, "\n");
copy (inf.begin(), inf.end(), output_iterator);
in.close( );
out.close( );
return 0;
}
最佳答案
您需要重载 operator<<
对于 info
:
std::ostream& operator<< (std::ostream& stream, const info& inf) {
return stream << inf.order << " " << inf.name;
}
关于c++ - 将 vector 输出到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026594/