主要在书写的时候不认真,但是意外发现了这个问题:
#include<iostream>
using namespace std;
#include<string>
#include <stdlib.h>
//结构体案例 ,三个老师分别带五个学生
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()%61+40;
tArray[i].sArray[j].score=random;
}
}
}
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;
}
}
}
int main()
{
//1、创建三名老师的数组
struct Teacher tArray[3];
//2、通过函数给三位老师赋值
int len=sizeof(tArray)/sizeof(tArray[0]);
allocatespace (tArray,len);
//3、打印所有的信息
printinfo(tArray, len);
system("pause");
return 0;
}
查找资料说:可能在VS中不会报错但是DEV中会报错的
当您在for标题中定义i时,它的范围在for循环内.您不能在循环之外使用它,而我的for循环后面加了”;”号,导致我的循环在分号哪里就结束了,我下面的语句就不属于循环里的东西了,所以才会报错。去掉分号之后就能顺利的运行了。
查找资料,也发现别人也有这样的问题,其中一个解决办法是在for循环之外定义i: