【发布时间】:2014-04-13 12:24:34
【问题描述】:
我正在尝试编写 C++ 代码以将 .csv 文件中的值输入到 C++ 中的矩阵。 .csv 文件包含浮点值,大小通常 >100x100。 我无法得到否。 .csv 文件中的行和列。它们来自 Matlab 代码,该代码生成大约 10 个不同大小的 .csv 文件。因此,我需要能够自动获取 .csv 文件的大小(以行和列为单位),以便可以在 C++ 代码中删除二维数组。
C++ 代码是:
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <iostream>
/*const int ROWS = 2;
const int COLS = 7;*/
const int BUFFSIZE = 80;
int main()
{
char buff[BUFFSIZE];
std::ifstream file("file.csv");
std::string line;
int col = 0;
int row = 0;
int a = 0, b = 0;
while (std::getline(file, line))
{
std::istringstream iss(line);
std::string result;
while (std::getline(iss, result, ','))
{
col = col + 1;
std::cout << col;
}
row = row + 1;
std::cout << "\n";
col = 0;
}
float array[row][col];
while (std::getline(file, line))
{
std::istringstream iss(line);
std::string result;
while (std::getline(iss, result, ','))
{
array[a][b] = atof(result.c_str());
b = b + 1;
}
a = a + 1;
b = 0;
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << array[i][j] << " ";
}
std::cout << "\n";
}
return 0;
}
打印循环的输出只是空白。 .csv 文件包含 2x7。我怎样才能解决这个问题?是不是因为istringsteam() 和getLine() 的多次使用。
请帮忙。请注意,我仍然是 C++ 的初学者。
【问题讨论】:
-
删除
col=0;声明。代码计算 cols 然后将 cols 设置为零。 -
您不能将运行时变量用作静态数组维度。您必须动态分配或使用向量:
std::vector<std::vector<float>> array(row, std::vector<float>(col))