c++ - 来自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;
}
解决方案
第四次尝试。基于这个线程的演变和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;
}
恕我直言,这比第三次尝试更复杂
推荐阅读
- javascript - 在 django 中使用 python 函数调用 javascript 函数
- java - 如何使用android中的动画将苹果放入篮子中?
- javascript - keystone.js 中的链式关系
- javascript - 字段验证器错误 Jquery
- xpath - XPATH - 在命名元素之后抓取 div 的内容
- html - 可以显示网页cookies的HTML按钮
- c# - 复合键、EF6 和插入顺序
- sql-server - 如何检查嵌套存储过程是否在 tsqlt 中执行
- reactjs - Keycloak json 配置文件,React 和 Router 4
- node.js - 环回验证在更新查询中不起作用?