c++ - 如何回到 csv 文件第一行的末尾?

标签 c++ csv ofstream

我正在使用 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/

相关文章:

c++ - 无法使用 square() 函数 c++

c++ - 重复使用相同的 ofstream 对象

c++ - ofstream- 将元素写入文件 - C++

c++ - 重置流但保留以前的数据

c# - C++ 是否有一些类似于 C# Type 的东西来将类的类型存储在列表/数组中?

python - 从 C++ 代码自动生成流程图

C++ 与 Eclipse 没有工具链?

python - 用今天的日期替换 CSV 文件中的 'NULL' 值 - Python

node.js - 在nodejs中从CSV文件获取数据

javascript - 使用 HTML5 在本地写入 CSV 文件