Hi....... I have a complicated homework...... I have a data which is csv file. I have to take this data from csv file and do sum calculations on these data's elements. But my problem is I cant take data from csv file to do this...
I can take data from dat or txt file with

printf( "%s %s %d %f",abc.x,abc.y,abc.z,abc.w);
fscanf("%s %s %d %f",abc.x,abc.y,&abc.z,&abc.w);

of course I have a structure on beginning my program and I know how to open file with fopen but it is not working when I try on csv file???
What is the difference why can not I do that????

note: when I take data from dat file there are only numbers or chars. but my csv file after every value there is a comma (,). Is this the problem???

PLease help.................

9 Years
Discussion Span
Last Post by vijayan121

Are you attempting to write a C or C++ program? This is the C++ board. If you really mean a C program then I or one of the other mods will move it the the C board.

Excactly how to read the CSV file depends on what character is used as field separator. Normall is a comma, but can also be space or tab.

In a C program, I would use fgets() to get the entire line, then strtok() to split it up into its individual fields.


if it is c++, using boost.tokenizer would be the easiest way.

#include <iostream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
#include <iterator>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;

struct abc
  explicit abc( const string& line ) ;
  string x ;
  string y ;
  int z ;
  double w ;

abc::abc( const string& line )
   typedef tokenizer< escaped_list_separator<char> > tokenizer ;
   tokenizer toker(line);
   tokenizer::iterator iterator = toker.begin() ;
   x = *iterator++ ;
   y = *iterator++ ;
   z = lexical_cast<int>( *iterator++ ) ;
   w = lexical_cast<double>( *iterator ) ;

int main()
  const char* const file_name = "csv.txt" ;
  // assumes file has data for one abc per line:
  // string x, string y, integer z, double w (seperated by commas)
  // if x or y contain embedded commas, they would be quoted strings (' or ")
  ifstream file( file_name ) ;
  vector<abc> elements ;
  string line ;
  while( getline( file, line ) )
    elements.push_back( abc(line) ) ; // will throw if there are errors
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.