【问题标题】:Writing 1D array to different columns in a CSV C++?将一维数组写入CSV C++中的不同列?
【发布时间】:2020-05-01 17:37:31
【问题描述】:

我有一个生成一维值数组的函数。我想将该数组存储到 CSV 文件中。每次调用该函数时,我都想将此数据存储到 CSV 中的新列中。现在我的代码是半工作的,每次我调用函数时它都会不断地将新的数据数组添加到我的 csv 中,但它会将它添加到同一列的底部。我希望将数据存储在下一列而不是添加到第一列的底部。任何帮助将不胜感激。

* 我删除了生成我的standard_dev数组的代码部分*

#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <iomanip>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "functions.h"

using namespace cv;
using namespace std;

void standard_deviation_line(Mat image, int column_count) {

    int sum = 0;
    int standard_dev_col = 0;
    int i, j; 
    const int cols = 3840;
    int rows = image.rows;
    float standard_dev[cols];
    float mean[cols];

ofstream out("SD.csv", ios::app);
    for (i = 0; i < cols; i++)
        out << standard_dev[i] << endl;

    out.close();

}

【问题讨论】:

    标签: c++ arrays csv append ofstream


    【解决方案1】:

    问题是你的 for 循环中的 endl,它输出一个换行符。

    ed:试试这个

    template<typename Iter>
    std::string join(Iter p0, Iter p1) {
        std::string result{};
        if(p0 != p1) {
            result = std::to_string(*p0++);
        }
        while(p0 != p1) {
            result += ',';
            result += std::to_string(*p0++);
        }
        return result;
    }
    

    然后像这样在没有 for 循环的情况下使用它:

    out << join(standard_dev, standard_dev + cols) << '\n';
    

    【讨论】:

    • 还不如告诉提问者他们应该输出什么来结束答案:逗号。
    • @user4581301 所以当我用 "," 替换 endl 时,它只会在我的 csv 中创建一行。一切都被覆盖了,它不会像我想要的那样在列中打印出来
    • 是时候让事情回到一个档次了。你怎么知道一行什么时候结束?
    • @user4581301 每次通过 for 循环都会创建一个新行。我第一次调用该函数时,它将所有值放在第 0 列中,并为每个值下拉一行。第二次调用该函数时,我希望它从第 1 列开始。
    • 作为一种临时解决方法,我只是在第一次调用函数时将所有内容打印在第 0 行,然后在函数结束时执行
    猜你喜欢
    • 2014-02-23
    • 2015-08-07
    • 1970-01-01
    • 2016-01-20
    • 2018-07-09
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    相关资源
    最近更新 更多