谁能帮助我,我正在尝试制作一个 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;
}
最佳答案
下次试试。非常简单的答案,只有基本结构。
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/