首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从c++中的csv文件中只读取一列?

如何从c++中的csv文件中只读取一列?
EN

Stack Overflow用户
提问于 2022-12-04 17:49:49
回答 2查看 30关注 0票数 -1

这里我有一个excel文件,它的第一列有ID的,即:ID 12 32 45 12。还有其他列,但我只想读取第一列中的数据,即ID。

这是我的代码,它会引发异常。我也不知道原因?

代码语言:javascript
运行
复制
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm> 
#include<string>
#include<cstdlib>
//std::find
#include<cstring>
using namespace std;
int main()
{
   

    ifstream fin("1.csv");
    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.
    std::vector<std::vector<std::string>> data;

    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)
            data[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;
string colName = "ID";

//1.Find the index of column name "computer science" on the first row, using iterator
//note: if "it == data[0].end()", it means that that column name was not found 
vector<string>::iterator it = find(data[0].begin(), data[0].end(), colName);

//calulate its index (ie: column number integer)  
colNum = std::distance(data[0].begin(), it);

//2. Print the column with the header "computer science"
for (int row = 0; row < rowCount; row++)
{
    cout << data[row][colNum] << "\t";  //print every value in column 47 only
}
cout << endl;

return 0;
}

请帮我解决这个问题。我只想显示包含ID的第一列。

EN

回答 2

Stack Overflow用户

发布于 2022-12-04 18:28:24

以下是上述代码的简化版本。它去掉2D向量,只读取第一列。

代码语言:javascript
运行
复制
std::vector<std::string> data;
ifstream fin("1.csv");
string line;
while (getline(fin, line)) //for every line in input file
{
    stringstream ss(line);  //copy line to stringstream
    string value;
    if (getline(ss, value, ',')) {
        data.push_back(value);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2022-12-04 18:29:32

问题是:

代码语言:javascript
运行
复制
std::vector<std::vector<std::string>> data;

分配一个vector of vector。两个维度当前都设置为0。

代码语言:javascript
运行
复制
data[rowIdx].push_back(value);

推入内部vector并可能调整其大小,但外部向量仍然大小为0。rowIdx的值无效。天真的解决方案是使用rowCount来调整外部vector的大小,但结果证明这是一种浪费。您可以组装整行,然后将该行push_backdata中,但即使这样也是浪费的,因为只需要一个列。

向量的优点之一是你不需要知道行数。创建行向量,将列推入其中,然后将行推入数据中。当你到达文件的末尾时,你就不会再读了。不需要读取文件两次,但您可能在数据的最后一次自调整大小上牺牲了一些浪费的存储空间。

代码语言:javascript
运行
复制
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
// reduced includes to minimum needed for this example
// removed using namespace std; to reduce odds of a naming collision
int main() {

    std::ifstream fin("1.csv"); // Relative path, so watch out for problems 
                                // with working directory
    std::string line;
    std::vector<std::string> data; // only need one column? Only need one 
                                   // dimension
    if (fin.is_open())
    {
        while (std::getline(fin, line)) //for every line in input file
        {
            std::stringstream ss(line);
            std::string value;
    
            if (std::getline(ss, value, ',')) 
            {
                 // only take the first column If you need, say, the third 
                 // column read and discard the first two columns 
                 // and store the third
                data.push_back(value); // vector sizes itself with push_back, 
                                       // so there is no need to count the rows
            }
        }
    }
    else
    {
        std::cerr << "Cannot open file\n";
        return -1;
    }
    // use the column of data here
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74679310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档