【问题标题】:Trying to populate an array using a function in C++ [closed]尝试使用 C++ 中的函数填充数组 [关闭]
【发布时间】:2014-03-28 02:55:07
【问题描述】:

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

#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 条数据,我只是不知道如何使用我创建的函数可靠地将文件中的数据获取到数组中。

任何帮助将不胜感激!

【问题讨论】:

  • 那行应该只是说populate(planesArray);。您不应该在每次使用变量时都提及它的类型。
  • @BrianBi 现在我已经为函数头做了这个,它说我需要 , 或 ;在 { 令牌之前。
  • 在函数头中,您确实需要类型。将其视为函数参数的声明。

标签: c++ arrays pass-by-value


【解决方案1】:
int main() {
  planes planesArray[5];
  populate( planesArray); // this is how to call your function
}
^^^
note:  ; disappeared

当你调用一个给定参数的函数时,你没有提到这个参数的类型。

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

【讨论】:

  • 它仍然不会填充数组,但出于不同的原因。
  • 真正的问题,并且肯定首先 OP 要克服的是编译
【解决方案2】:

数组不适合 C++ 中的此类任务,特别是如果您是该语言的新手。使用std::vector - 并将“planes”重命名为“plane”,这样更有意义(您的结构代表 一个 平面,不多)。

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

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

这应该可以解决最明显的错误。

【讨论】:

  • std::array 对于固定数量的对象也是一个不错的选择。它基本上就像一个没有问题的 C 样式数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多