0

I am pretty new to C++. I just want to get a certain field on a ".csv" file, not all off it. I am pretty sure, it must be very easy, but I don't know how to do it. Here is my code to get all the ".csv" content :

#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 Answers2

3

If you can use boost libraries, then boost::tokenizer would provide the functionality you require. Most notablty, it correctly handles quoted field values that contain commas. The following is a code snippet copied from the linked page:

// 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";
   }
}

You could pass each ligne read to a tokenizer and extract the fields you require.

hmjd
  • 120,187
  • 20
  • 207
  • 252
2

Try reading whole lines and split them afterwards:

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)
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198