在C++中获取.csv文件的列数和行数

Getting the number of columns and rows of a .csv file in C++

本文关键字:文件 C++ 获取 csv      更新时间:2023-10-16

我正在尝试编写C++代码,将.csv文件中的值输入到C++中的矩阵中。.csv文件包含浮点值,大小通常大于100x100。我无法从.csv文件中获取行数和列数。它们来自Matlab代码,该代码生成大约10个大小不等的.csv文件。因此,我需要能够自动获得.csv文件的大小(以行和列为单位),以便在C++代码中对2D数组进行delcare。

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。我该怎么解决这个问题?是因为CCD_ 1和CCD_。请帮忙。请注意,我仍然是C++的初学者。

您忘记了在第二个循环之前移回流的位置。在最后一个while()循环结束后,流到达末尾。您现在必须清除错误状态并返回(您也可以关闭并重新打开文件):

file.clear();
file.seekg(0, std::ios_base::beg);

此外,不能将运行时变量用作静态数组维度。如果您的编译器支持非标准扩展,那么它将使用非标准扩展。您必须动态分配或使用向量:

std::vector<std::vector<float>> array(row, std::vector<float>(col))

您可以计算任意行中的逗号数,"count+1"将是.csv文件中的列数。

对于行数,你可以简单地写这样的东西——

int rows=0;
ifstream file("xyz.csv");
string line;
while (getline(file, line))
rows++;

这里的"行"是.csv文件中的行数。

如果需要示例,请检查此存储库。