gpt4 book ai didi

c++ - 在 C++ 中将 vector 写入 csv

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:44:34 26 4
gpt4 key购买 nike

我正在尝试用 C++ 将 vector 写入 .csv final,但 .csv 文件的格式错误。

我目前正在这样做:

    ofstream myfile(rtn);
int vsize = returns.size();
for(int n=0; n<vsize; n++)
{
myfile << returns[n] << '\t';
myfile << "," ;
}

哪个有效,但它会像这样写 vector :

a,b,c,d, (所有在一行但不同的列)

我需要代码来写:

 a
b
c
d

所有内容都在一列中,但在不同的行中。有没有人对我如何着手提出建议?

谢谢!

最佳答案

您可以隐式循环遍历 vector 。将 std::cout 替换为 std::ofstream 以输出到文件。

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {

std::vector<std::string> v;
v.push_back("a");
v.push_back("b");
v.push_back("c");

std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n"));


return 0;
}

关于c++ - 在 C++ 中将 vector 写入 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com