尝试使用 C++ 中的函数填充数组

Trying to populate an array using a function in C++

本文关键字:函数 填充 数组 C++      更新时间:2023-10-16

所以,我正在尝试使用函数填充和打印一个小数组,但是我遇到了一些障碍。我拥有的代码是:

#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]);
};

我在使用的代码的不同迭代中遇到了许多错误。上面粘贴了这个,我得到:

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

老实说,我有点迷茫。数组中有 5 条数据,我只是不知道如何使用我创建的函数可靠地将数据从文件获取到数组中。

任何帮助将不胜感激!

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

当你调用给定某个参数的函数时,你不会提到这个参数的类型。

接下来,您将尝试实现您的函数。目前,它对数组参数没有任何作用,但我们不会提供现成的调谐解决方案,而是在您遇到一些具体问题时提供帮助。

数组不适合

C++这样的任务,特别是如果你不熟悉这门语言。使用 std::vector - 并将"planes"重命名为"plane",这更有意义(您的结构表示一个平面,而不是多个平面)。

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

这应该可以修复最明显的错误。