向文件写入向量结构

时间:2014-05-11 23:18:28

标签: c++ file vector struct

所以我有一个像这样的简单结构:

struct scores
{
    std::vector<double> max_score,min_score;
    std::vector<string> names;
};

scores sc;

然后我创建:包含多个字符串的向量 sc.names ,并对包含分数的 max / min_scores 执行相同操作。


现在,我只是无法弄清楚如何将所有3个向量并排(列)写入文件,如下所示:

name1 max_score1 min_score1

name2 max_score2 min_score2

...

std::ofstream testwrite;
testwrite.open("test.txt");

testwrite << std::setprecision(4);
testwrite << std::fixed;
for (std::vector<double>::iterator it = sc.max_score.begin();it != sc.max_score.end();++it)
{
    testwrite << *it << "\n";
}

testwrite.close();

1 个答案:

答案 0 :(得分:2)

如果您确定向量的长度相同,则可以迭代索引:

for (int i=0; i < sc.max_score.length(); ++i)
  testwrite << sc.names[i] << " " << sc.max_score[i] << ... << std::endl;