首页 > 解决方案 > 来自csv文件的C ++中多维数组的总和

问题描述

谁能帮助我,我正在尝试制作一个 C++ 程序,它从 csv 文件中读取值并打印它们(将有 3 个 4 行 3 列)。我想知道如何添加行(例如第一行的总和=?第二行的总和=?...)

矩阵如下所示:

在此处输入图像描述

我的程序看起来像:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    
    ifstream sumCol;
    sumCol.open("Col.csv");
    
    string line;
    int sum;
    
    cout << "The entered matrix: " << endl;
    while(sumCol.good()){
        string line;
        getline(sumCol, line, ',');
        cout << line << "  ";
    }

    while(sumCol.good()){
        getline(sumCol, line, ',');
        int i = stoi(line);
        cout << endl; 
        cout << i;
    }
    
    
  while(getline(sumCol, line, ',')){
        int i = stoi(line);
        sum = sum + i;
        
        getline(sumCol, line, ',');
        i = stoi(line);
        sum = sum + i;
        
        getline(sumCol, line);
        i = stoi(line);
        sum = sum + i;
    }
    
    cout << sum << endl;
    
    return 0;
}

标签: c++

解决方案


第四次尝试。基于这个线程的演变和OP使用的请求std::getline

#include <iostream>
#include <fstream>
#include <string>

int main() {

    // Open file 
    std::ifstream csv("r:\\col.csv");

    // and check, if it could be opened
    if (csv) {

        // Now the file is open. We have 3 rows and 4 columns
        // We will use 2 nested for loops, one for the rows and one for the columns

        // So, first the rows
        for (int row = 0; row < 3; ++row) {

            // Every row has a sum
            int sumForOneRow = 0;

            // And every row has 4 columns. Go through all coulmns of the current row.
            for (int col = 0; col < 4; ++col) {

                // Read a substring up to the next comma or end of line
                std::string line;

                // Special handling for last column. This is not followed by a comma
                if (col == 3)
                    std::getline(csv, line);
                else
                    std::getline(csv, line, ',');

                // Convert string to line
                int integerValue = std::stoi(line);

                // Show it on the screen
                std::cout << integerValue << ' ';

                // Update the sum of the row
                sumForOneRow = sumForOneRow + integerValue;
            }
            // Now, the inner for loop for the 4 columns is done. Show sum to user
            std::cout << " --> " << sumForOneRow << '\n';

            // Line activities are done now for this line. Go on with next line
        }

    }
    else std::cerr << "\n*** Error: Could not open 'col.csv'\n";
    return 0;
}

恕我直言,这比第三次尝试更复杂


推荐阅读