簡體   English   中英

如何在C ++中獲取.csv文件的一部分?

[英]How to get part of an .csv file in C++?

我對C ++很陌生。 我只想在“ .csv”文件上獲取某個字段,而不是全部關閉。 我很確定,這一定很容易,但是我不知道該怎么做。 這是獲取所有“ .csv”內容的代碼:

#include <iostream>
#include <fstream>
#include <string>
// #include "Patient.h"

using namespace std;

int main()
{
    // CPatient patient; 

    ifstream file("C:/Users/Alex/Desktop/STAGE/test.csv");


    if(file)
    {
         // the file did open well

        string line;      

        while(getline(file, line, ';'))    //Until we did not reach the end we read
        {

            cout << line << endl; //Console Result

        }
    }
    else
    {
        cout << "ERROR: Could not open this file." << endl;
    }
    system("PAUSE");
    return 0;
}

如果可以使用boost庫,則boost::tokenizer將提供您所需的功能。 最明顯的是,它可以正確處理包含逗號的帶引號的字段值。 以下是從鏈接頁面復制的代碼段:

// simple_example_2.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main(){
   using namespace std;
   using namespace boost;
   string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
   tokenizer<escaped_list_separator<char> > tok(s);
   for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin();
       beg!=tok.end();
       ++beg)
   {
       cout << *beg << "\n";
   }
}

您可以將每個ligne讀取傳遞給tokenizer然后提取所需的字段。

嘗試閱讀整行,然后將其拆分:

int N = 5; // search the fifth field
char separator = ';';
while (std::getline(fichier, ligne)) {
    // search for the Nth field
    std::string::size_type pos = 0;
    for (int i = 1; i < N; ++i)
        pos = ligne.find_first_of(separator, pos) + 1;

    std::string::size_type end = ligne.find_first_of(separator, pos);
    // field is between [pos, end)
}

暫無
暫無

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

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