使用固定数组而不是数组会让事情变得更加困难vector
of vector<int>
对于你的二维数组。另外,为了解析.csv
文件,读取每个完整行,然后创建一个stringstream
从行中解析getline
using ','
终止符,然后使用stoi
将字段转换为整数值 (C++11) 使过程非常简单。
例如,将要读取的文件名作为程序的第一个参数,您可以将上述内容实现为:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main (int argc, char **argv) {
string line; /* string to hold each line */
vector<vector<int>> array; /* vector of vector<int> for 2d array */
if (argc < 2) { /* validate at least 1 argument given */
cerr << "error: insufficient input.\n"
"usage: " << argv[0] << " filename\n";
return 1;
}
ifstream f (argv[1]); /* open file */
if (!f.is_open()) { /* validate file open for reading */
perror (("error while opening file " + string(argv[1])).c_str());
return 1;
}
while (getline (f, line)) { /* read each line */
string val; /* string to hold value */
vector<int> row; /* vector for row of values */
stringstream s (line); /* stringstream to parse csv */
while (getline (s, val, ',')) /* for each value */
row.push_back (stoi(val)); /* convert to int, add to row */
array.push_back (row); /* add row to array */
}
f.close();
cout << "complete array\n\n";
for (auto& row : array) { /* iterate over rows */
for (auto& val : row) /* iterate over vals */
cout << val << " "; /* output value */
cout << "\n"; /* tidy up with '\n' */
}
return 0;
}
(note:提供的自动内存管理string
and vector
将允许您读取任何大小的数组(最多达到虚拟内存的限制),而无需事先知道字段数或行数。您可以添加简单的计数器来验证每行包含相同数量的值,等等...)
输入文件示例
$ cat file.txt
1,1,1
1,2,3
3,1,3
使用/输出示例
$ ./bin/iostream_sstream_csv_stoi file.txt
complete array
1 1 1
1 2 3
3 1 3
检查一下,如果您还有其他问题,请告诉我。