Reading a particular line in a csv file in C++ -


this question has answer here:

i have csv file contains many rows of data. function passes linenum argument. when user enters 4 linenum want read 4th line in csv file. thought way go through \n 's , count them,stop when count linenum-1, , proceed read next line. think decent way of doing this, thoroughly confused implementation. love here code

void readcsv( int linenum){     ifstream infile ("/media/logging/darsv1.csv");     string line;     string dataarray[226900];     int = 0;     int endofline =0;     int a, b, c, d, e;     while (getline (infile, line)) {         //printf(line.c_str());         istringstream linestream(line);         string item ="";         int itemnum = 0;         if (linenum==1) {             printf(" line number 1. ");             while (getline (linestream, item, ',')) {             itemnum++;             dataarray[i]=item;             i++;             }         }         else {             while (getline (linestream, item,'\n')) {                 endofline=endofline+1;                 cout<<"  went through line number  "<<endofline<<" ";                 printf(" inside inner while, looking line. ");                 if (endofline == linenum-1) {                     printf(" found correct line. ");                     while (getline (linestream, item, ',')) {                         itemnum++;                         dataarray[i]=item;                         i++;                         printf(" found correct data in line. ");                     }                 }             }printf(" out of inner while. ");         }printf(" out of outer if. ");    }    printf(" out of while loops. "); } 

if need read line in csv , line read comma separated items might help. agree @sanjaya-r should keep simple.

#include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std;  int main (int argc, const char * argv[]) {     string line, csvitem;     ifstream myfile ("/tmp/file.csv");     int linenumber = 0;     int linenumbersought = 3;  // may argument     if (myfile.is_open()) {         while (getline(myfile,line)) {             linenumber++;             if(linenumber == linenumbersought) {                 cout << line << endl; ;                 istringstream myline(line);                 while(getline(myline, csvitem, ',')) {                     cout << csvitem << endl;                 }             }         }         myfile.close();     }     return 0; } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -