榕树贷款C++ STL 中没有内置 CSV 读取器/写入器

C++读写CSV文件
据我所知,C++ STL 中没有内置 CSV 读取器/写入器。这不是对 C++ 的打击。榕树贷款只是一种低级语言。如果我们想用 C++ 读写 CSV 文件,榕树贷款将不得不处理文件 I/O、数据类型和一些关于如何读取、解析和写入数据的低级逻辑。对我来说,这是构建和测试更多有趣程序(如机器学习模型)的必要步骤。

榕树贷款写入CSV
这里,ofstream是一个“输出文件流”。由于它派生自ostream,我们可以像对待cout一样对待它(它也是派生自ostream)。执行这个程序的结果是,榕树贷款在可执行文件所在的目录中得到了一个名为ones.csv的文件。让我们将它封装到write_csv()函数中。

#include <string>
#include <fstream>
#include <vector>

void write_csv(std::string filename, std::string colname, std::vector<int> vals){
    // Make a CSV file with one column of integer values
    // filename - the name of the file
    // colname - the name of the one and only column
    // vals - an integer vector of values
    
    // Create an output filestream object
    std::ofstream myFile(filename);
    
    // Send the column name to the stream
    myFile << colname << "\n";
    
    // Send data to the stream
    for(int i = 0; i < vals.size(); ++i)
    {
        myFile << vals.at(i) << "\n";
    }
    
    // Close the file
    myFile.close();
}

int main() {
    // Make a vector of length 100 filled with 1s
    std::vector<int> vec(100, 1);
    
    // Write the vector to CSV
    write_csv("ones.csv", "Col1", vec);
    
    return 0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值