How to read-write into/from text file with comma separated values


How do I read data from a file if my file is like this with comma separated values

1, 2, 3, 4, 5\n
6, 7, 8, 9, 10\n

and after reading the file, I want to write the data back into other file as same format above.

I can get total number of lines, using

string line;
    numline--; // remove the last empty line

but how can I know total number of digits in a row/line ??

I also have vector of ints to store the data. So, I want to read the first line and then count total number of elements in that line, here 5 (1,2,3,4,5) and store them in array/vector, and read next line and store them in vector again and so on till I reach EOF.

Then, I want to write the data to file, again, I guess this will do the job of writing data to file,

for(int i = 0; i < vector.size(); i++)
    file <<;
    if((numOfCols<5) file << ",";//print comma (,)
                  file << endl;//print newline after 5th value
                  numOfCols=1;//start from column 1 again, for the next line
file << endl;// last new line

So, my main problem is how to read the data from file with comma separated values ??


12/25/2013 8:39:12 PM

Accepted Answer

Step 1: Don't do this:


The EOF is not true until you try and read past it. The standard pattern is:


Also note that std::getline() can optionally take a third parameter. This is the character to break on. By default this is the line terminator but you can specify a comma.

    std::stringstream   linestream(line);
    std::string         value;

        std::cout << "Value(" << value << ")\n";
    std::cout << "Line Finished" << std::endl;


If you store all the values in a single vector then print them out using a fixed width. Then I would do something like this.

struct LineWriter
        LineWriter(std::ostream& str,int size)

        // The std::copy() does assignement to an iterator.
        // This looks like this  (*result) = <value>;
        // So overide the operator * and the operator = to
        LineWriter& operator*() {return *this;}   
        void operator=(int val)
                m_str << val << (((m_current % m_size) == 0)?"\n":",");

        // std::copy() increments the iterator. But this is not usfull here
        // so just implement too empty methods to handle the increment.
        void operator++()       {}
        void operator++(int)    {}

        // Local data.
        std::ostream&           m_str;
        int const               m_size;
        int                     m_current;

void printCommaSepFixedSizeLinesFromVector(std::vector const& data,int linesize)
5/3/2018 12:55:33 PM

here I m posting the code for CSV read as well as write code. I have checked its working fine.

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;

void readCSV(istream &input, vector< vector<string> > &output)
   string csvLine;
    // read every line from the stream
    while( getline(input, csvLine) )
            istringstream csvStream(csvLine);
           vector<string> csvColumn;
            string csvElement;
            // read every element from the line that is seperated by commas
            // and put it into the vector or strings
            while( getline(csvStream, csvElement, ',') )

int main()
    ofstream myfile;
    string a;
    fstream file("b.csv", ios::in); ("ab.csv");
           cout << "File not found!\n";
            return 1;
    // typedef to save typing for the following object
    typedef vector< vector<string> > csvVector;
    csvVector csvData;

    readCSV(file, csvData);
    // print out read data to prove reading worked
    for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
            for(vector<string>::iterator j = i->begin(); j != i->end(); ++j)
                  cout << a << " ";
          myfile <<a<<",";

 myfile <<"\n";
 cout << "\n";


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow