The first getline
extracts a complete line from the input.
The second extracts one field from the next line. If you want
to recover the lines broken down into fields, you should do:
std::vector<std::vector<std::string>> records;
std::string line;
while ( std::getline( f, line ) ) {
records.push_back( std::vector<std::string>() );
std::istringsream fieldParser( line );
std::string field;
while ( std::getline( fieldParser, field ) ) {
records.back().push_back( field );
}
}
This will result in a vector of records, where each record is a vector of fields. More often, you would want to use a struct for the record, and do a bit more parsing on the line, e.g.:
struct Field
{
std::string firstName;
std::string lastName;
int age;
std::string country;
};
std::vector<Field> records;
std::string line;
while ( std::getline( f, line ) ) {
std::istringsream fieldParser( line );
Field field;
fieldParser >> field.firstName >> field.lastName >> field.age >> field.country >> std::skipws;
if ( !fieldParser || fieldParser.get() != EOF ) {
// Error occurred...
} else {
records.push_back( field );
}
}
(Something this simple will only work if none of the fields may contain white space. But it's simple to extend.)