Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading in from a text file with multiple information

Status
Not open for further replies.

sharktlp

Technical User
Nov 19, 2003
5
0
0
US
I made a class which will store all the information of a list of employees. I want to know how to read in from a file and seperate the information into where i want it like the adress as employee.address or the gender as employee.gender. I was trying to use getline but its not working how i want it to work. The text file looks like this:
Employee: John e. smith
address: 12 maple street new jersey, nj, 12345
phone number: 2341231222
gender: male
age:22
dependants:2
department:construction
union:yes
hourly rate:10.25

Employee: mark e. tan
address: 12 dark street new yokr, ny, 12345
phone number: 123456222
gender: male
age:29
dependants:2
department:sales
union:no
hourly rate:15.25


The text file will contain a lot more employees
 
I suggest basic elements. Use
Code:
#include <iostream>
#include <fstream>
#include <string>
typedef string::size_type Pos;
namespace { // Locals
const Pos eos = string::npos;
} // End locals
// Split xxxx:yyyy text as key (xxxx) and val (yyyy)
bool Split(string& s, string& key, string& val)
{
  Pos col = s.find(':');
  if (col != eos)
  {
    key = s.substr(0,col);
    val = s.substr(col+1);
  }
  else
  {
    key = &quot;&quot;;
    val = s;
  }
  return col != eos;
}
...
istream is;
string s, key, val;
...
if (!getline(is,s).eof()) // Read next line, check eof cond
{
  if (Split(s,key,val) && key == &quot;Employee&quot;) // Next record
  {
  ...
Key issues:
1. Use STL istream& getline(istream&,string&), not a member getline functions.
2. Split source line with find/substr string member functions (see my Split for example).
3. Now you may implement any desired alg to import data. If you can terminate record reading on &quot;hourly rate:&quot; line - that's OK, convert and save record values then go to next record. If not, you may stop on the next &quot;Employee:&quot; line and don't forget save it and start next record processing from it.
You may buffer (pack) main stream input into your own class, you may use std:map<string,string> for intermediate input record form, or use straightforward approach with line by line input loop...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top