Having issues with an ifstream function

I have to make a function that reads data from a given file to a structure with a definition given below:

1
2
3
4
5
  struct craft {
int n;
float m;
float c[3];
};


The given file has a header which states the number of rows of data in the file. And each data point in the file corresponds to the order which it appears in the structure. As it stands now my function looks like this:

1
2
3
4
5
6
7
  craft getcraft(ifstream& fin) {
    
    craft A;
    int c; float b,ax,ay,az;
      fin >> A.num >> A.m >> A.c[0] >> A.c[1] >> A.c[2];
  return A;
}


That function then has to be used in a loop to load each output as an element in an array of structures with the "craft" form like so:

 
for (int i=0;i<N;i++) pieces[i] = getcraft(fin);


What should I do differently for my function for it to return a structure of that form?
Last edited on
> What should I do differently for my function for it to return a structure of that form?
¿ah? ¿isn't doing that already?

you create a `Part'... ¿why do you create a `Part' instead of a `craft'?
Last edited on
Fixed that issue but it still isn't working. The program runs it just doesn't input the correct data.
Try this: First you could teach the ifstream reading in a craft struct:
1
2
3
4
5
std::istream& operator>> (std::istream& istr, craft& c)
{
     istr >> c.n >> c.m >> c.c[0] >> c.c[1] >> c.c[2];
    return istr;
}

This overloads the >> operator for std::istream. Because ifstream is derived from istream, this will work.

Then you could use that like:
1
2
3
4
5
6
7
8
9
10
11
12
    ....
    std::ifsteam ifstr("put_here_a_file_name");
    std::vector<craft> vec_cr;
    int number_of_structs;
    ifstr >> number_of_structs;
    for (int i = 0; i < number_of_structs; ++ i)
    {
        craft c;
        if (istr >> c) vec_cr.push_back(c);
        else return EXIT_FAILURE;
    }
    ...

If something is unclear to you, feel free to ask (after you've done research in the Reference rubric).
Last edited on
Topic archived. No new replies allowed.