How to extract data from a line whose fields are separated by '|' character in C ++?


I have data in the following format in a text file. Filename - empdata.txt Note that there are no blank space between the lines.


1|327427|Brock Mcneil|Research and Development|U2|Pune

2|310456|Acton Golden|Advertising|P3|Hyderabad

3|305540|Hollee Camacho|Payroll|U3|Bangalore

4|218801|Simone Myers|Public Relations|U3|Pune

5|144051|Eaton Benson|Advertising|P1|Chennai

I have a class like this

class empdata
int sl,empNO;
char name[20],department[20],band[3],location[20];

I created an array of objects of class empdata. How to read the data from the file which has n lines of data in the above specified format and store them to the array of (class)objects created?

This is my code

int main () {
string line;
ifstream myfile ("empdata.txt");
for(int i=0;i<10;i++) //processing only first 10 lines of the file
    getline (myfile,line);
    //What should I do with this "line" so that I can extract data
    //from this line and store it in the class object?             


  return 0;

So basically my question is how to extract data from a string which has data separated by '|' character and store each data to a separate variable

I prefer to use the String Toolkit. The String Toolkit will take care of converting the numbers as it parses.

Here is how I would solve it.

#include <fstream>
#include <strtk.hpp>   //

using namespace std;

// using strings instead of character arrays
class Employee
    int index;
    int employee_number;
    std::string name;
    std::string department;
    std::string band;
    std::string location;

std::string filename("empdata.txt");

// assuming the file is text
std::fstream fs;, std::ios::in);

if(  return false;   

const char *whitespace    = " \t\r\n\f";

const char *delimiter    = "|";

std::vector<Employee> employee_data;

// process each line in turn
while( std::getline(fs, line ) )

// removing leading and trailing whitespace
// can prevent parsing problemsfrom different line endings.

    strtk::remove_leading_trailing(whitespace, line);

    // strtk::parse combines multiple delimeters in these cases

    Employee e;

    if( strtk::parse(line, delimiter, e.index, e.employee_number,, e.department,, e.location) )
         std::cout << "succeed" << std::endl;
     employee_data.push_back( e );