尝试使用 C++ 中的函数填充数组
Trying to populate an array using a function in C++
所以,我正在尝试使用函数填充和打印一个小数组,但是我遇到了一些障碍。我拥有的代码是:
#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);
}
这应该可以修复最明显的错误。
相关文章:
- 如何将零填充的多维数组传递给 C++ 中的函数?
- 填充上编译器生成的复制构造函数之间的不一致
- 如何使用(lambda)函数填充C++容器
- 从函数填充的字符串的推导向量到 int 的字符串
- parallel_for lambda 函数填充 2D 向量后出错
- 在使用结构体和用函数填充其变量(使用指针)时遇到问题
- 尝试使用函数填充2维数组
- 如何使用静态函数填充静态 std::map
- 使用 C 函数填充 QByteArray
- 尝试用函数填充线程向量 - 错误
- 如何使用FormatMessage函数填充系统错误消息的va_list
- 使用枚举指定的函数填充矢量
- 为什么我不能用这个其他类的函数填充这个类的函数指针
- 函数填充向量,但它在某个时刻变为空
- 使用函数填充数组中的数字.如果数组已满,则该数字将在第二个数组中填充
- 用函数c++填充指针数组
- 使用派生类构造函数填充基类受保护成员
- 用构造函数填充向量的C++奇怪行为
- 使用/不使用c++内部函数填充
- 返回Boost分布生成器从函数填充向量在c++中