View Single Post
Old Jun 22nd, 2005, 1:27 PM   #6
Eggbert
Professional Programmer
 
Eggbert's Avatar
 
Join Date: Nov 2004
Posts: 250
Rep Power: 5 Eggbert is on a distinguished road
>anyone plese tell me how to read data from such kind of txt files..
With a CSV parsing library. Comma separated values files are surprisingly difficult to parse manually if you follow the full CSV specification. A naive approach would ignore some of the details and still work for many cases, but break for anything unexpected or relying on certain CSV details such as the double double quote for embedded double quotes:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

using namespace std;

vector<string> csv_parse ( const string& s );

int main()
{
  string line ( "\"1\",868000,3917200,\"(868000.0,3917200.0)\"" );

  cout<<"Original line: "<< line <<'\n';
  cout<<"CSV separated line:\n";

  vector<string> v = csv_parse ( line );

  copy ( v.begin(), v.end(), ostream_iterator<string> ( cout, "\n" ) );
}

vector<string> csv_parse ( const string& s )
{
  string::const_iterator first = s.begin();
  string::const_iterator last = s.end();
  vector<string> v;
  string field;

  while ( first != last ) {
    switch ( *first ) {
    case ',':
      v.push_back ( field );
      field.clear();
      break;
    case '"':
      while ( ++first != last && *first != '"' )
        field.push_back ( *first );
      break;
    default:
      field.push_back ( *first );
      break;
    }

    ++first;
  }

  if ( field != "" )
    v.push_back ( field );

  return v;
}
Eggbert is offline   Reply With Quote