开发者

Calculating sums of columns in CSV file using C++

开发者 https://www.devze.com 2023-02-19 21:13 出处:网络
How can I calculate sums of columns from CSV file using C++? My csv file 22 4533 85070 46088 And I want the result in an array some thing like this

How can I calculate sums of columns from CSV file using C++?

My csv file

22 45  33
8  50  70
4  60  88

And I want the result in an array some thing like this

34 155 190

can i add开发者_如何学C a formula in a csv file using c programming


#include <iostream>
#include <fstream>

int main(int argc, char *argv[]) {
    std::ifstream in;
    int array[3] = {0, 0, 0};
    if (argc < 2)
        return 1;

    in.open(argv[1], std::ifstream::in);
    while (in.good()) {
        int one, two, three;
        in >> one >> two >> three;
        array[0] += one;
        array[1] += two;
        array[2] += three;
    }

    std::cout << array[0] << ' ' << array[1] << ' ' << array[2] << std::endl;
    in.close();

    return 0;
}

Something like that?


Store the sum in an array:

int val;
int sum[column];

for each row in csv file
    for each column i in csv file
        val = atoi(read_value_from_file())
        sum[i] += val
    end for
end for


You can store the table in a 2D array and then you can calculate the sum of elements in columns using simple for loop. Check this repository for getting code for the same. Hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消