0

I'm having some trouble with a programming project. I want to get information from a .txt document, and store the information in an array of class objects. For each line of the .txt document, I want a new class object to be created.

So if there was

"10 Mark 9/24/1988 accounts manager

9 Jenny 8/6/1983 shipping assistant"

in the .txt, the first line would be stored in the variables of the first object at uArray[0] and the second line would be stored in the variables of uArray[1].

I've created a class "users" with five variables.

int iD;
string name, birth, sSN, dept, position;

This is what I have, I know it is way, way off, but I can't get it right..

{
ifstream myFile;
users uArray[100];

myFile.open("users.txt")
while(!myFile.eof())
   {
   myFile >> uArray.users.iD >> uArray.users.name >> uArray.users.sSN ...(ect);
   }
}

Should I create a function to call that will sort the information or is there an easier way? I'm stuck... Sorry for the beginner's questions...

stringgy
  • 85
  • 1
  • 1
  • 9
  • One obvious error is the `while` loop. See [here](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) for more on that. – juanchopanza Apr 13 '13 at 07:54

3 Answers3

2

You can overload the operator>> to make this a little easier. This is the actual purpose behind operator overloading. You provide a custom behavior and it is completely transparent when using streams. Declare a friend-function inside your class

friend std::ifstream& operator>>(std::ifstream&, users& user);

and implement it

std::ifstream& operator>>(std::ifstream& stream, users& user){
    stream >> user.iD >> user.name >> user.sSN ...(ect)
    return stream;
}    

You can then use a for-loop and do as you did above. But you must use array-indices to address single elements within the array

int i = 0;
while(!myFile.eof())
{
    myFile >> uArray[i].users.iD >> uArray[i].users.name >> 
    uArray[i].users.sSN ...(ect);
    i++;
}

See here for a tutorial.

bash.d
  • 12,357
  • 2
  • 24
  • 37
0

You need something more akin to this, where you are indexing into the array:

ifstream myFile;
users uArray[100];

myFile.open("users.txt")
i=0;
while(!myFile.eof())
{
    myFile >> uArray[i].iD >> uArray[i].name >> uArray[i].sSN ...(ect);
    i++;
}
dan
  • 965
  • 8
  • 24
0

You're not accessing the elements of uArray correctly. Since it's an array (of size 100 in your example), you need to specify which array element you want to load data into, as in

uArray[i].users.iD

One solution to your problem is to have a variable that's incremented for every record in your file:

int index = 0;
while ( !myFile.eof() && index < 100 ) {
    myFile >> uArray[index].users.iD >> ...;
    index++;
}

BTW, you'll get extra points if you give the "100" value a name (either as a #define or as a const int), and use that value to compare index against.

radical7
  • 8,192
  • 3
  • 20
  • 32