c++ - 来自csv文件的C++中多维数组的总和

标签 c++

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

#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;
}

最佳答案

下次试试。非常简单的答案,只有基本结构。
12 个陈述。但是 2 个 for 循环,行和列的嵌套和硬编码魔数(Magic Number)。
请参阅以下注释良好的源代码:

#include <iostream>
#include <fstream>

int main() {

    // Open file 
    std::ifstream csv("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 an integer value from the current line
                int integerValue;
                csv >> integerValue;

                // 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;
}

关于c++ - 来自csv文件的C++中多维数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62849883/

相关文章:

c++ - 为什么 C++ 中的多维数组在传递给函数时表现不同?

c++ - 我总是在运行这个程序时遇到无限循环。

c++ - 如何在 C++ 中对 vector 组元素进行排序?

C++11 带有可变参数列表的 lambda 函数

c++ - __forceinline 的执行速度是否比 __inline 快?

java - 用C++做游戏还是用java做游戏?

c++ - 如何从 QFile 中读取带符号的 16 位整数?

c++ - 用 boost::shared_ptr<std::list<T>> 初始化 boost::shared_ptr<std::vector<T>>

c++ - Visual Studio (2015) C 项目依赖项 - 必须定义 LNK1561 入口点

c++ - 如何将 WT 小部件放入 PDF?