如何从CSV文件获取指定列?代码push_back语句报错求助
CSV读取指定列的类型错误分析与解决
问题描述
尝试从CSV文件中提取指定列时,执行ptr[rowIdx].push_back(value)语句出现错误:no suitable conversion from string to char。出错代码如下:
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include<string.h> #include<cstdlib> //std::find #include<cstring> using namespace std; int main(int argc, char** argv) { ifstream fin("filename"); string line; int rowCount = 0; int rowIdx = 0; //keep track of inserted rows //count the total nb of lines in your file while (getline(fin, line)) { rowCount++; } //this will be your table. A row is represented by data[row_number]. //If you want to access the name of the column #47, you would //cout << data[0][46]. 0 being the first row(assuming headers) //and 46 is the 47 column. //But first you have to input the data. See below. string *ptr=new string[rowCount]; fin.clear(); //remove failbit (ie: continue using fin.) fin.seekg(fin.beg); //rewind stream to start while (getline(fin, line)) //for every line in input file { stringstream ss(line); //copy line to stringstream string value; while (getline(ss, value, ',')) { //for every value in that stream (ie: every cell on that row) ptr[rowIdx].push_back(value);//add that value at the end of the current row in our table } rowIdx++; //increment row number before reading in next line } fin.close(); //Now you can choose to access the data however you like. //If you want to printout only column 47... int colNum = 1; //set this number to the column you want to printout for (int row = 0; row < rowCount; row++) { cout << ptr[row][colNum] << "\t"; //print every value in column 47 only } cout << endl; return 0; }
问题根源
- 数据结构不匹配:你声明的
string *ptr=new string[rowCount];是一个字符串数组,每个元素是单个std::string对象。但std::string::push_back()的参数要求是char类型,你传入的却是std::string类型的value,直接导致类型转换错误。 - 逻辑设计偏差:注释里明确要实现“表格”结构(每行包含多列数据),但当前数组只能存储每行作为单一字符串,无法拆分不同列的内容;后续的
ptr[row][colNum]访问方式也是错误的——这里的[colNum]是访问字符串的第colNum个字符,而非第colNum列的值。
修正方案
使用**二维向量std::vector<std::vector<std::string>>**存储CSV数据,每行对应一个字符串向量,每个元素代表一列的值。修正后的代码如下:
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> using namespace std; int main(int argc, char** argv) { ifstream fin("filename"); string line; vector<vector<string>> data; // 二维容器存储整个CSV表格 // 逐行读取并分割列,无需预统计行数 while (getline(fin, line)) { stringstream ss(line); string value; vector<string> currentRow; // 存储当前行的所有列值 while (getline(ss, value, ',')) { currentRow.push_back(value); // 将列值加入当前行 } data.push_back(currentRow); // 将当前行加入表格 } fin.close(); // 提取指定列(示例:第2列,索引为1) int colNum = 1; for (const auto& row : data) { // 避免列索引越界 if (colNum < row.size()) { cout << row[colNum] << "\t"; } else { cout << "N/A\t"; } } cout << endl; return 0; }
额外优化说明
- 移除了未使用的头文件,精简代码结构。
- 利用
std::vector的动态扩容特性,省去预统计行数的步骤,简化逻辑。 - 添加列索引越界判断,避免程序崩溃。
内容的提问来源于stack exchange,提问作者i210510 Abdullah Zafar
相关产品推荐
相关产品推荐

