C ++逐个传递一个Struct数组 - 这么简单,但我很难过

时间:2011-04-19 02:43:10

标签: c++ arrays data-structures

首先感谢所有帮助的人!

我试图在这里一次传递一个变量而不是整个数组。我知道我很亲密,但我已经搜索过,无法找出我做错了什么。

出现错误我说它是

  

void PrintRecords(studentRec& myRec)

它说:字段'PrintRecords'的变量声明为void

#include <iostream>
using namespace std;

struct studenRec {
  string name;
  string address;
  string city;
  string state;
  string zip;
  char gender;
  string myid;
  float gpa;
};

void PrintRecords(studenRec& myRec);

int main() 
{
  studenRec myRec[3];

  for (int i = 0; i < 3; i++) {
    cout << "Students name: ";
    getline(cin, myRec[i].name);
    cout << "Students address: ";
    getline(cin, myRec[i].address);
    cout << "Students city: ";
    getline(cin, myRec[i].city);
    cout << "Students state: ";
    getline(cin, myRec[i].state);
    cout << "Students zip: ";
    getline(cin, myRec[i].zip);
    cout << "Students gender: ";
    cin >> myRec[i].gender;
    cin.ignore(1000,10);
    cout << "Students id: ";
    getline(cin, myRec[i].myid);
    cout << "Students gpa: ";
    cin >> myRec[i].gpa;
    cin.ignore(1000,10);
    cout << "STUDENT RECORDED SUCCESSFULLY" << endl;
    cout << endl;
  }

  cout << "-------------------------------" << endl;

  for (int i = 0; i < 3; i++) {
    PrintRecords(myRec[i]);
  }

  return 0;
} // main

void PrintRecords(studentRec& myRec)
{
  cout << "Students name: " << myRec.name << endl;
  cout << "Students address: " << myRec.address << endl;
  cout << "Students city: " << myRec.city << endl;
  cout << "Students state: " << myRec.state << endl;
  cout << "Students zip: " << myRec.zip << endl;
  cout << "Students gender: " << myRec.gender << endl;
  cout << "Students id: " << myRec.myid << endl;
  cout << "Students gpa: " << myRec.gpa << endl;
  cout << endl;
}

3 个答案:

答案 0 :(得分:3)

您已声明为struct StudenRecord {};这似乎是一个错字。随处更改为StudentRecord

答案 1 :(得分:2)

你的原型有一个额外的逗号。这一行:

void PrintRecords(studenRec&, myRec);

应该是:

void PrintRecords(studenRec& myRec);

答案 2 :(得分:2)

你的功能

void PrintRecords(studentRec& myRec)

对结构studentRec进行单一引用,而不是数组。所以当你使用代码时

for (int i = 0; i < 3; i++) {
  PrintRecords(myRec[i]);
}

您说“循环遍历数组中的所有三个项目并将每个实例逐个传递到函数PrintRecords”,这意味着每当调用PrintRecords时,它只访问其中一个实例。

然而,在函数printRecords中,您正在访问myRec,就好像它是一个数组,实际上它只是对恰好位于数组中的对象的单个引用。正确的功能应如下所示:

void PrintRecords(studentRec& myRec)
{
  cout << "Students name: " << myRec.name << endl;
  cout << "Students address: " << myRec.address << endl;
  cout << "Students city: " << myRec.city << endl;
  cout << "Students state: " << myRec.state << endl;
  cout << "Students zip: " << myRec.zip << endl;
  cout << "Students gender: " << myRec.gender << endl;
  cout << "Students id: " << myRec.myid << endl;
  cout << "Students gpa: " << myRec.gpa << endl;
  cout << endl;
}