如何在C 中获取.CSV文件的一部分

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

本文关键字:CSV 文件 一部分 获取      更新时间:2023-10-16

我是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)
}