在C++中获取.csv文件的列数和行数
Getting the number of columns and rows of a .csv file in C++
我正在尝试编写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文件中的行数。
如果需要示例,请检查此存储库。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到