如何在 c++ 中跳过读取 csv 文件的第一列

How to skip the first column reading csv file in c++

本文关键字:一列 文件 csv c++ 读取      更新时间:2023-10-16

下面的代码是从csv文件中获取一些数据。但结果如下所示:

5,琼斯,123-123-1234,BCBS,GP1234,39,莎拉,断臂,3

6,史密斯,123-231-1234,UHC,G1234,47,弗朗辛,物理治疗,03/25/2015

9,亚当斯,123-123-4321,信诺,U1234,28,鲍勃,断臂,2

5,梵高,123-321-1234,BCBS,GP1235,37,安德里亚,肚子痛,3

10,

锡器施密特,123-312-1234,UHC,G1112,42,Peter,监督正常第一次怀孕,03/26/2015

但是我想获取除第一列以外的数据(例如5,6,9,5,10(我该怎么做?你能给我一个想法吗?谢谢。

void Hospital::readRecordsFile()
{
    fileName = "Waterbury Hospital patients records.csv";
    ifstream file(fileName);
    string value;
    vector <string> getInform;
    while(file.good())
    {
        getline(file, value);
        getInform.push_back(value);
        //getInform.erase(getInform.begin()+1);
    }
    for(int i=0;i<getInform.size();i++)
    {
        cout << getInform[i] << endl;
    }
}

您可以在每行中找到第一个分隔符 (,(,然后删除它之前的所有字符:

getline(file, value);
const auto pos = value.find(',');
if(pos != string::npos)
    value.erase(0, pos + 1);

如果您不确定 CSV 文件中是否使用了分隔符 (,(。您可能会忽略每行开头的所有数字:

getline(file, value);
const auto pos = value.find_first_not_of("0123456789");
if(pos != string::npos)
    value.erase(0, pos + 1);

>std::istream::ignore可用于忽略输入流中的某些文本。

从输入流中提取和丢弃字符,直到并包括delim

file.ignore(std::numeric_limits<std::streamsize>::max(), ',');

并用getline跟进以阅读该行的其余部分。

getline(file, value);

您应该用","拆分每一行,然后忽略第一部分。

只需解析字符串以丰富第一个","字符,然后使用该索引中的子字符串到结尾。