将矢量输出到文件中

时间:2014-11-19 20:43:07

标签: c++

我正在尝试创建一个程序,打开一个包含此格式名称列表的txt文件(忽略项目符号):

  • 3马克
  • 4拉尔夫
  • 1 Ed
  • 2 Kevin

并将根据前面的数字创建一个带有组织名称的文件:

  • 1 Ed
  • 2 Kevin
  • 3马克
  • 4拉尔夫

我无法将矢量输出到新文件“outfile.txt” 在第198行,我得到错误“不匹配'运算符<< ...< ...”

我可以使用哪些其他方法输出载体?

#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;
}

2 个答案:

答案 0 :(得分:1)

您需要重载operator<<的{​​{1}}:

info

答案 1 :(得分:1)

您甚至可以为输入端重载operator>>

std::istream& operator>>(std::istream& is, info& i) {
    return std::getline(is >> i.order, i.name);
}
std::ostream& operator<<(std::ostream& os, info const& i) {
    return os << i.order << " " << i.name;
}

这使您可以为输入/输出实现更一致的代码:

<强> Live On Coliru

int main() {
    std::ifstream in ("infile.txt");
    std::ofstream out("outfile.txt");

    if (!in || !out) {
        std::cout << "file opening failed\n";
        return 1;
    }

    std::vector<info> inf;

    std::copy(std::istream_iterator<info>(in), {}, back_inserter(inf));
    std::sort(inf.begin(), inf.end());
    std::copy(inf.begin(), inf.end(), std::ostream_iterator<info>(out, "\n"));
}