Start New Discussion within our Software Development Community

I have here a problem...
i have a notepad containing values such as:
tom,a1001,1
charles,1002,2

I used getline() and used the delimiter comma to separate them and store it in line variable..
my problem is that how can i store the delimited strings from line variable to any different variables..

ex .tom should be stored in employee variable or a1001 should be stored in idnumber variables.

Here's my lacking code:
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>

using namespace std;


void main()
{
string line;
string filename="employee.txt";
ifstream myfile;
myfile.open(filename.c_str());

if(myfile.fail())
{
cout<<"Unable to open file named"<<filename<<endl;
exit(1);
}
while(myfile.good())
{
getline(myfile,line,',');

cout<<line;
}
}
Please help me..

You could write a class that is a representation of one line of your file - eg. Name, code1, code2.
Then you could store a vector (see STL vector.h - an array you can keep adding to) of these classes. Each time you read a line you could create a new class, pass the line to a method in your class that extracts the data - eg. InitFromCSV(char*);
Then add this to your vector.

Customer newCustomer; // Customer - the name of your new class
newCustomer.InitFromCSV(line); // Write this method to extract the data into members of your class
customerVector.push_back(newCustomer); // push_back adds a new element to the STL vector

You'll then have a list of all the data in your file.
You can then loop through them all like an array:

for(int i = 0, n = customerVector.size(); i < n; ++i)
{
    Customer& customer = customerVector[i];
    // Do stuff with customer.
}
This article has been dead for over six months. Start a new discussion instead.