求解答,感谢,我尝试在结构体中插入新的信息,想的是1,输入指定位置;2,指定位置,和数组内4321的倒序循环,比较,就比如我输入插到第3个位置,循环会帮助我找到第三个位置,然后将第三个位置后包括第三个位置的结构体向后移动,但是我的结果是第三个新的信息替换掉了原来第三个位置的信息,请问如何成功将第三个位置的结构体向后移动一位?
void InsertNew(){//指定位置插入新的学生信息
int p=0,i;
STU temp1={0};
printf("Please enter the position where you want to insert the student information. \n"
"If you want to put the information in the first place, enter 1\n");
scanf("%d",&p);//输入指定的位置
for(i=NUM-2;i>=0;i--)
{
if(p <= stu[i].o){//循环实现,将指定内容后的数组内容向后移动一位
stu[i+1]=stu[i];
}
else{//移动后将输入信息插入到指定位置
break;
}
}
printf("Please input student information:");
printf("Student ID(zy00*)\n");
scanf("%s",stu[p-1].id);
getchar();//Absorb extra line breaks
printf("name\n");
scanf("%s",stu[p-1].name);
printf("Please input the score of each subject\n");
stu[p-1].sum=0;
for(int j =0;j<3;j++)
{
scanf("%f",&stu[p-1].ach[j]);
stu[p-1].sum +=stu[p-1].ach[j];
}
getch();
}
这个地方,你这样改一下
for(i=NUM-2;i>=p-1;i--)
{
stu[i+1]=stu[i];
}
我理解的这个地方 NUM,指的是结构体总数+1
如果你的NUM代表的是学生总数的话,这样改
for(i=NUM-1;i>=p-1;i--)
{
stu[i+1]=stu[i];
}
循环后移错了,代码修改如下:
void InsertNew(){//指定位置插入新的学生信息
int p=0,i;
STU temp1={0};
printf("Please enter the position where you want to insert the student information. \n"
"If you want to put the information in the first place, enter 1\n");
scanf("%d",&p);//输入指定的位置
//修改为
for (i = NUM-1;i>= p;i++)
{
stu[i] = stu[i-1]; //循环后移
}
/*for(i=NUM-2;i>=0;i--)
{
if(p <= stu[i].o){//循环实现,将指定内容后的数组内容向后移动一位
stu[i+1]=stu[i];
}
else{//移动后将输入信息插入到指定位置
break;
}
}*/
printf("Please input student information:");
printf("Student ID(zy00*)\n");
scanf("%s",stu[p-1].id);
getchar();//Absorb extra line breaks
printf("name\n");
scanf("%s",stu[p-1].name);
printf("Please input the score of each subject\n");
stu[p-1].sum=0;
for(int j =0;j<3;j++)
{
scanf("%f",&stu[p-1].ach[j]);
stu[p-1].sum +=stu[p-1].ach[j];
}
getch();
}
void InsertNew(){//指定位置插入新的学生信息
int p=0,i;
STU temp1={0};
printf("Please enter the position where you want to insert the student information. \n"
"If you want to put the information in the first place, enter 1\n");
scanf("%d",&p);//输入指定的位置
p--;
for(i=NUM-2;i>=p;i--)
{
//循环实现,将指定内容后的数组内容向后移动一位
stu[i+1]=stu[i];
}
printf("Please input student information:");
printf("Student ID(zy00*)\n");
scanf("%s",stu[p].id);
getchar();//Absorb extra line breaks
printf("name\n");
scanf("%s",stu[p].name);
printf("Please input the score of each subject\n");
stu[p].sum=0;
for(int j =0;j<3;j++)
{
scanf("%f",&stu[p-1].ach[j]);
stu[p].sum +=stu[p-1].ach[j];
}
getch();
}