我正在使用 ofstream 编写一个 csv 文件。 目前,我使用“<<”运算符从左到右编写它,这很容易。 例如,
Shape,Area,Min,Max
Square,10,2,11
Rectangle,20,3,12
我想改成这样
Shape,Square,Rectangle
Area,10,20
Min,2,3
Max,11,12
我知道我可以使用“<<”运算符并以这种方式编写它,但我正在使用一些循环并且不可能使用“<<”运算符那样编写它。
所以我正在寻找一种写顺序的方法,例如
Shape,
Area,
Min,
Max,
然后变成
Shape,Square
Area,10
Min,2
Max,1
所以它基本上是从上到下而不是从左到右。 如何使用 ofstream 对此进行编码?我猜我必须使用 seekp,但我不确定如何使用。 非常感谢。
最佳答案
除了在 ostream 的末尾,你不能插入 覆盖已经写入的数据。对于什么之类的 你正在尝试做,你可能必须收集每一行 单独的字符串(可能使用 ostringstream 来编写),然后 输出行。像这样的东西:
std::ostringstream label;
label << "Shape";
std::ostringstream area;
area << "Area";
std::ostringstream min;
min << "Min";
std::ostringstream max;
max << "Max";
for (std::vector<Shape>::const_iterator> it = shapes.begin();
it != shapese.end();
++ it)
{
label << ',' << it->TypeName();
area << ',' << it->Area();
min << ',' << it->min();
max << ',' << it->max();
}
dest << label.str() << '\n';
dest << area.str() << '\n';
dest << min.str() << '\n';
dest << max.str() << '\n';
关于c++ - 如何回到 csv 文件第一行的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5407660/