```c++
#include
#include
#include
using namespace std;
struct Student //学生的结构体定义
{
string sName;
int score{};
};
struct Teacher //老师的结构体定义
{
string tName;
struct Student sArray[5];
};
void allocateSpace(struct Teacher tArray[],int len)
{
string nameSeed = "ABCDE";
for (int i = 0; i < len; i++) //给老师开始赋值
{
tArray[i].tName = "Teacher_";
tArray[i].tName += nameSeed[i];
for (int j = 0; j < 5; j++)
{
tArray[i].sArray[j].sName = "Student_";
tArray[i].sArray[j].sName += nameSeed[j];
int random = rand() % 101;
tArray[i].sArray[j].score = random;
}
}
}
void printInfo(struct Teacher tArray[i], int len) //打印所有信息
{
for (int i = 0; i < len; i++)
cout << "老师姓名: " << tArray[i].tName << endl;
for (int j = 0; j < 5; j++)
{
cout << "\t学生姓名: " << tArray[i].sArray[j].sName <<"考试分数: "<int main()
{
srand((unsigned int)time(NULL));
struct Teacher tArray[3];//创建三名老师的数组
//通过函数给3名老师的信息赋值,并给老师带的学生信息赋值
int len = sizeof(tArray) / sizeof(tArray[0]);
allocateSpace(tArray, len);
//打印所有老师及所带的学生信息
printInfo(tArray,len);
system("pause");
return 0;
}
```
cout << "\t学生姓名: " << tArray[i].sArray[j].sName <<"考试分数: "<
printInfo方法有问题,修改如下:
void printInfo(struct Teacher tArray[], int len) //打印所有信息
{
for (int i = 0; i < len; i++)
{
cout << "老师姓名: " << tArray[i].tName << endl;
for (int j = 0; j < 5; j++)
{
cout << "\t学生姓名: " << tArray[i].sArray[j].sName <<"考试分数: "<<tArray[i].sArray[j].score<<endl;
}
}
}
请问各位专家解释一下为什么代码会在这一行的tArray[i]中报错未定义标识符i
==因为在.NET环境下,for循环定义的int i循环变量的作用域只在这个for循环内部,所以在第二个循环内是不认识这个i变量的。这个和VC6下是不同的。修改方法只能是将循环变量i在for循环之前定义,这样第二个循环就能访问到这个i变量了
=======
不过从你的代码逻辑看,错误原因是第二个循环应该属于第一个循环的内部循环,而不是并列循环,因此你需要将第二个循环放到第一个循环的大括号内才行,就像你前面那个函数一样
void printInfo(struct Teacher tArray[i], int len) //打印所有信息
{
for (int i = 0; i < len; i++)
{
cout << "老师姓名: " << tArray[i].tName << endl;
for (int j = 0; j < 5; j++)
{
cout << "\t学生姓名: " << tArray[i].sArray[j].sName <<"考试分数: "<<tArray[i].sArray[j].score<<endl;
}
}
}