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

时间:2012-10-30 08:48:49

标签: c++ csv

我对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;
}

2 个答案:

答案 0 :(得分:3)

如果您可以使用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并提取您需要的字段。

答案 1 :(得分:2)

尝试阅读整行并将其拆分:

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