簡體   English   中英

如何在C ++中跳過讀取CSV文件的第一列

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

下面的代碼是從csv文件中獲取一些數據。 但是結果顯示如下:

5,瓊斯,123-123-1234,BCBS,GP1234,39,莎拉,斷臂,3

6,Smith,123-231-1234,UHC,G1234,47,Francine,Physical Therapy,03/25/2015

9,亞當斯,123-123-4321,Cigna,U1234,28,鮑勃,斷臂,2

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

10,Pewterschmidt,123-312-1234,UHC,G1112,42,Peter,監督正常第一次懷孕,2015年3月26日

但是我想獲取第一列以外的數據(例如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);

您應將每行均用','分隔,然后忽略第一部分。

只需解析字符串以豐富第一個','字符,然后使用該索引中的子字符串結束即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM