/* FileParser.cpp */ #include "FileParser.h" /* int main() { string buffer; FileParser fp ( "sample.csv" ); while ( fp.NextField( buffer ) ) cout << buffer << endl; return 0; } */ /* Constructor for FileParser class * param: string object containing filename * */ FileParser::FileParser(string input_file) { input = new ifstream( input_file.c_str() ); // initialize file stream if ( input->is_open() == false ) { // error checking cerr << "The input file cannot be opened.\n"; exit(1); } getline(*input,line_buffer); // get first line of input from *input // and store in line_buffer member } /* Nextfield method * Gets next comma-separated field from the input stream * and puts it in string parameter field_buffer * */ int FileParser::NextField(string & field_buffer) { unsigned int end; end = line_buffer.find(","); // get position of next comma if ( end != line_buffer.npos ) { // if comma exists in line_buffer field_buffer = line_buffer.substr(0, end); // this is the output field line_buffer = line_buffer.substr(end+1, line_buffer.size() ); // // shrink line_buffer return 1; } else { // no more commas field_buffer = line_buffer; // output remaining chars to end-of-line if (*input) { // check for end of file stream getline(*input,line_buffer); return 1; } else return 0; } }