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

Viewed 90312

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
\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;
while(!file.eof()){
      getline(file,line);
      numlines++;
    }
    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,

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

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

Thanks

3 Answers

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, ',') )
            {
                    csvColumn.push_back(csvElement);
            }
            output.push_back(csvColumn);
    }
}

int main()
{
    ofstream myfile;
    string a;
    fstream file("b.csv", ios::in);
    myfile.open ("ab.csv");
    if(!file.is_open())
    {
           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)
            {
          a=*j;
                  cout << a << " ";
          myfile <<a<<",";

 }
 myfile <<"\n";
 cout << "\n";
 }
 myfile.close();
 system("pause");

}
Related