Trying to populate an array using a function in C++ [closed]

妖精的绣舞 提交于 2019-12-22 01:09:12

问题


So, I'm trying to populate and print a small array using functions, however I've hit a bit of a roadblock. The code I have is:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

struct planes
{
    string name;
    int seats;
    int range;
    int weight;
};

int populate (planes planesArray[5])
{
    string name;
    int seats, range, weight, i;
    ifstream infile;
    infile.open("plane_data.txt");
    if (!infile)
    {
        cout << "File cannot be reached";
    }

    for (int i = 0; i < 4; i++){
        infile >> name;
        infile >> seats;
        infile >> range;
        infile >> weight;

    }

    infile.close();

}



int main() {

    planes planesArray[5];
    populate(planes planesArray[5]);

};

I'm getting a multitude of errors in the different iterations of code I'm using. With this one pasted above I am getting:

line 44: error: expected primary expression before (planesArray)

I'm a bit lost to be honest. There are 5 pieces of data in the array, I just don't know how to get the data from the file into the array reliably using the functions I've created.

Any help would be much appreciated!


回答1:


int main() {
  planes planesArray[5];
  populate( planesArray); // this is how to call your function
}
^^^
note:  ; disappeared

When you call a function given some parameter you do not mention type of this parameter.

Next, you will try to implement your function. At the moment it does nothing with array parameter, but we won't provide ready tuned-in solution but rather help when you meet some concrete problems.




回答2:


Arrays are unfit for such a task in C++, especially if you are new to the language. Use std::vector - and rename "planes" to "plane", which makes more sense (your struct represents one plane, not many).

int populate (std::vector<plane> &plane_vector)
{
  // ...
}

int main()
{
  std::vector<plane> plane_vector;
  populate(plane_vector);
}

This should fix the most blatant errors.



来源:https://stackoverflow.com/questions/22021745/trying-to-populate-an-array-using-a-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!