Storing data from a file into an array

Ok, so I'm given let's say a set of data in a .txt file that reads:

width
length
height
area
width
length
height
area
width
length
height
area

How do you just put all the length datas into an array, like ignoring or overwriting everything but length.

I had already opened the file and got the data like this, which I believe is correct?

int main()
{
ifstream rectangle;
string line;

rectangle.open ("rectangle.txt", ifstream::in);
if (!rectangle)
{
return -1;
}

while (rectangle.good())
{
getline(rectangle, line);

}
rectangle.close();

return 0;
}
Last edited on
The easiest way is to use a structure:
1
2
3
4
5
6
7
struct entry
{
    int width;
    int length;
    int height;
    int area;
};


Then if you want to input your structure without much hassel:
1
2
3
4
5
6
7
8
9
std::ifstream& operator>>(std::ifstream& fin, entry& rhs)
{
    fin >> rhs.width;
    fin >> rhs.length;
    fin >> rhs.height;
    fin >> rhs.area;

    return fin;
}


That function will let you do the following:
1
2
3
4
5
std::ifstream fin("mYDoc.txt");
entry MyEntry[3];

for (int i = 0; i < 3; ++i)
    fin >> MyEntry[i];
Yes, I realize that using a struct would be much easier, however, I am not allowed to do that in my assignment which is why I'm completely clueless on how to do this
Maybe something like that:
1
2
3
4
5
6
7
8
9
10
std::ifstream fin("mYDoc.txt");
int length[3], tmp;

for (int i = 0; i < 3; ++i)
{
    fin >> tmp; // width
    fin >> length[i];
    fin >> tmp; // area
    fin >> tmp; // height
}
In that case use parallel arrays:
1
2
3
4
5
6
7
8
9
int width[3];
int length[3];
int height[3];
int area[3];

for (int i = 0; i < 3; ++i)
{
    fin >> width[i] >> length[i] >> height[i] >> area[i];
}
He said he wants to ignore everything but length.
I mean, I don't really know. What we have to do is for the read function, open the file, pull out the four lines at a time till eof, take the 2nd line (length), put that into an array (which is passed by reference) and then return nothing. Then in the main function we have to define the array, call the read function, and when the array is done being built, find the sum of the contents and print out the sum. And we are given this function prototype: void read_data(ifstream& input, int arr[]); to pass the array as a parameter. I am just completely confused, but thanks for trying to help me.
Topic archived. No new replies allowed.