如何在C++中将数值型CSV读取到二维数组(禁用vector等高级工具)
读取CSV到二维数组的最简C++实现
直接上满足需求的代码,核心解决你提到的stringstream读取后换行的问题——std::getline会自动把文件指针移到下一行,不用手动处理:
#include <iostream> #include <fstream> #include <sstream> #include <string> int main() { // 定义固定大小的二维数组,4000行3列,用double兼容整数和浮点数 double data[4000][3]; std::ifstream input_file("your_file.csv"); // 替换成你的CSV文件名 std::string line; int current_row = 0; // 逐行读取,直到文件读完或者填满数组 while (std::getline(input_file, line) && current_row < 4000) { std::stringstream line_stream(line); std::string field; int current_col = 0; // 按逗号拆分当前行的每个字段 while (std::getline(line_stream, field, ',') && current_col < 3) { // 把字符串转成浮点数存入数组 data[current_row][current_col] = std::stod(field); current_col++; } current_row++; } input_file.close(); // 可选:打印前几行验证读取结果 for (int i = 0; i < 5; i++) { std::cout << data[i][0] << ", " << data[i][1] << ", " << data[i][2] << "\n"; } return 0; }
关键说明
std::getline(input_file, line)每次调用会读取一整行,读完后自动将文件指针定位到下一行开头,完全不用手动调整指针- 用
stringstream拆分每行内容时,std::getline(line_stream, field, ',')会按逗号分割出每个数据字段 - 用
std::stod转换字符串到浮点数,整数会被自动转为对应的浮点值,兼容你的数据类型需求 - 直接用固定大小的二维数组,完全没用到vector等“高级工具”
内容的提问来源于stack exchange,提问作者Abdullah Dilshad
相关产品推荐
相关产品推荐

