【问题标题】:C++ reading into a struct array inside of a function?C ++读入函数内部的结构数组?
【发布时间】:2016-05-27 20:13:36
【问题描述】:

我试图将一个 int 读入一个结构数组,但在尝试编译时,我在 '[' 之前收到了预期表达式的错误。

struct department {
    int id;
    char name[20];
};

int addnewdep(struct department[],int d);
int main()
{
.....
}
int addnewdep(struct department[],int d)
{
    cin >> department[d].id;
    cin >> department[d].name;
}

错误出现在函数定义中。 我不确定如何解决此错误。在这方面的任何帮助都会很棒,谢谢。

【问题讨论】:

  • 函数定义上多了一个;
  • 修复了这个问题,它最初不在我的代码中,所以仍然是同样的错误。
  • struct department 是类型的名称。虽然它在声明中起作用,但您需要在定义中使用参数名称:int addnewdep(struct department[],int d){...} 应该是 int addnewdep(struct department department[],int d){...},如果您希望在引用它时将参数命名为 department

标签: c++ arrays function struct


【解决方案1】:

应该是:

  int addnewdep(department dep[], int d) {
     cin >> dep[d].id;
     cin >> dep[d].name;
  }

因为部门是类型的名称,而不是函数的参数。另请注意额外;在你的代码中。

不需要在定义之前声明 addnewdep()。

【讨论】:

  • 感谢它并没有完全修复它,但是当我在定义和原型中将它更改为 int addnewdep(struct department dep[],int d) 时,它修复了我的错误。谢谢。
  • 你还需要struct keywordstruct department dep[]
猜你喜欢
  • 1970-01-01
  • 2013-10-27
  • 2018-01-29
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多