0

I'm trying to write a simple function that reads a csv while and stores each line into a vector. The code is given below:

   vector<string> readCSVfile( string path )
   {    
      ifstream ohlcStream( path );      

      istream_iterator<string> start(ohlcStream), end;
      vector<string> ohlcData(start, end);  
      ohlcStream.close();
      return ohlcData;
   }

However for some reason the lines of the file seem to be delimited by both white spaces and line breaks. The first line of the raw data file for example looks like this:

  Date,Open,High,Low,Close,Adj Close,Volume,factor,date_downloaded

but after calling the function in main:

    vector<string> mydata = readcsv( path );

and outputting the elements of the vector, mydata, I get:

    element 0: Date,Open,High,Low,Close,Adj 
    element 1: Close,Volume,factor,date_downloaded

even though I was expecting:

     Date,Open,High,Low,Close,Adj Close,Volume,factor,date_downloaded

I have tried to use

    ohlcStream >> noskipws;
    istream_iterator<string> start(ohlcStream), end;

But that didn't work. What results is a vector that is empty.

I know that I could use getline and loop but I would like understand why my current code just isn't working.

Any help would be appreciated. thanks

Ray Ng
  • 1
  • 1
    [`std::istream_iterator`](http://en.cppreference.com/w/cpp/iterator/istream_iterator) uses the normal `>>` operator to read the input from the stream. And when `>>` reads strings, it reads **space-delimited** "words". You can't use it for CSV files, and I suggest you find a library to handle it for you (because CSV files are only *seemingly* simple to parse). – Some programmer dude Feb 01 '18 at 03:36
  • 1
    [How can I read and parse CSV files in C++?](https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c) – R Sahu Feb 01 '18 at 03:51

0 Answers0