我正在尝试打印在“show”void中的“getvalue”void中找到的值。我得到一个错误:
错误:“学生”未在此范围中声明
#include <iostream>
using namespace std;
int studentNumber=0;
int testNumber=0;
struct Student
{
string name,grade;
int studentNo,*testResults;
double average;
};
void getValue()
{
cout << "Enter the number of students: ";
cin >> studentNumber;
cout << "Enter the number of tests: ";
cin >> testNumber;
Student* Students = new Student[studentNumber];
for(int i=0; i< studentNumber; i++)
{
cout<< "\n" << "Enter the name of the " << i+1 << ". student: ";
cin >> Students[i].name;
cout<< "\n" << "Enter the number of the " << i+1 << ". student: ";
cin >> Students[i].studentNo;
Students[i].testResults = new int[testNumber];
for(int z=0; z<testNumber; z++)
{
cout<< "\n" << "Enter the " << z+1 << ". exam grade of the " << i+1 << ". student: " ;
cin >> Students[i].testResults[z];
}
}
}
void show()
{
for(int i=0; i < studentNumber; i++)
{
cout<< "\n" << Students[i].name;
cout<< "\n" << Students[i].studentNo;
for(int z=0; z<testNumber; z++)
{
cout<< "\n" <<Students[i].testResults[z];
}
}
}
int main()
{
getValue();
show();
}
我正试图在另一个名为“show”的虚空中显示获得的值,但失败了。(必须在一个不同的虚空中的代码的一般结构必须是我的作业中另一个名为“show”的虚空)
您必须传递值。
可以通过引用来完成:
// omit
void getValue(Student*& Students) // add reference argument
{
cout << "Enter the number of students: ";
cin >> studentNumber;
cout << "Enter the number of tests: ";
cin >> testNumber;
// don't declare here and use the arugment
Students = new Student[studentNumber];
// omit
}
void show(Student* Students) // add argument (need not be reference)
{
// omit
}
int main()
{
// add variable for arguments and use that
Student* s;
getValue(s);
show(s);
}
或通过全局变量:
// omit
// declare variable here (as global)
static Student* Students;
void getValue()
{
cout << "Enter the number of students: ";
cin >> studentNumber;
cout << "Enter the number of tests: ";
cin >> testNumber;
// don't declare here and use the global variable
Students = new Student[studentNumber];
// omit
}
void show()
{
// omit
}
int main()
{
getValue();
show();
}