我削减了我学生管理作业的这一部分,当我比较输入中的2个名字,1,我想要搜索1时,它打印出结果但立即崩溃。请帮忙。感谢您的回复,谢谢
class Student
{
public:
string name;
public:
void input();
};
class list
{
private:
Student ds[100];
int count=0;
int number,addnum=0;
int total=number+addnum;
public:
void input(int y);
void find();
friend class SinhVien;
};
void SinhVien::input()
{
fflush(stdin);
gotoXY(5,9);cout<<"name : ";
cin>>name;
}
void list::input(int y)
{
fflush(stdin);
createBox(2,5,63,20,7);
gotoXY(8,y-3);
cout<<"add student\n";
gotoXY(8,y-1);
if (count==0)
{
cout<<"number of students : ";
cin>>number;
for(int i=1; i<=number; i++)
{
gotoXY(8,7);
cout<<"student "<<i<<endl;
ds[i].input();
count++;
}
}
else if(count>0)
{
cout<<"number of student : ";
cin>>addnum;
for(int i=1; i<=addnum; i++)
{
ds[i+count].input();
count++;
}
}
}
void list::find()
{
int count=0;
string name1;
gotoXY(10,51);
cout<<"type name : ";
cin>>name1;
for(int i=0; i<total; i++)
{
string name2 =ds[i].name;
if( name1.compare(name2) ==0)
{
cout<<"yes";
count++;
}
}
if(count==0)
cout<<"not found";
}
int main()
{
list a;
a.input(1);
int x;
cin>>x;
if (x==1)
a.find();
}
答案 0 :(得分:4)
int number,addnum=0;
int total=number+addnum;
您将total
初始化为number+addnum
。但此时,number
尚未分配值。因此,分配给total
的值是垃圾。当你使用它来停止你的循环时,你的循环可能运行得太远而且访问数组越界。