Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Delimited Files Can Easily Be Read Using A While Loop And Getline

Delimited Files Can Easily Be Read Using A While Loop And Getline

C Programming Tricks

Delimited files can easily be read using a while loop and getline:

 Given data file: 
 
   John|83|52.2
   swimming|Jefferson
   Jane|26|10.09
   sprinting|San Marin
   
 Process using: 
 
 std::ifstream inf("data.txt");
 char name[30];
 while(!inf.getline(name, 30, '|').eof())
 {
   Athlete* ap;
   char jersey_number[10];
   char best_time[10];
   char sport[40];
   char high_school[40];
   inf.getline(jersey_number, 10, '|'); #read thru pipe
   inf.getline(best_time, 10);          #read thru newline
   inf.getline(sport, 40, '|');         #read thru pipe
   inf.getline(high_school, 40);        #read thru newline
   ap = new Athlete(name, strtod(number), strtof(best_time), sport, high_school);
   //do something with ap
 
 }
 

Partners