struct and reading from a file

First problem is how I would count how many people are in a certain file when the file follows :
April,Joe 312033387 12
Matthews,Jocob 459237148 39
Garfield,Kitty 891772436 33
Lake,Bill 223390100 21
Etc.. (name, id, distance)

Second is how to store these values using a struct array, and manipulating each Name, ID, and distance to complete this assignment.


My problem is not knowing how to cin each value independent of one another

If anyone could help/point me in the right direction, that would be very great.
Last edited on
I'm going to just give you the highlights:

Define a structure with the variables for each item.

Create an array of these structures.

If the file is stored as binary, you can read right into each structure.

If they are delimited (like your example) then call cin for each variable in the structure and increment the array's offset so that your next set of reads will use the next structure in the array and so on.
For the first, assuming that no. of persons = no. of lines,
while( std::getline( my_file, my_string ) ) count++;.
You will then have to go back to the beginning of the file with fstream::seekg().

For the second, if you know how to cin, what is the problem? Making a struct array?
1
2
3
4
struct Record{
   std::string name;
   int some_random_number, another_random_number;
};

1
2
Record rec[50];//or Record* rec = new Record[number];
for(int i = 0; i < /*something*/; i++) //cin rec[i].name, and numbers... 
well the struct is defined as

1
2
3
4
5
struct Node
{
char name[30];
long SSN;
int distance;


i guess i'm just having trouble understanding what to do or even use this info.
Like Hamsterman said, you'll need an array of Nodes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   
#define NODE_SIZE 50

Node NodeArray[ 50 ];

for( int i = 0; i < NODE_SIZE; i++ )
    {
    cin >> rec[ i ].name ;

    cin >> rec[ i ].SSN ;

    cin >> rec[ i ].distance;

    }    /*    for( i < NODE_SIZE )    */


Now this doesn't check for enc of file, and 50 may be too few structures for your array.
Topic archived. No new replies allowed.