我正在编写一个列出学生并添加学生的C程序,但是当我添加一个新学生时,虽然我可以成功读取该值,但该函数只能将前2个元素打印到屏幕上,而无法正确读取新添加的元素.
代码在这里:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef char str[50];
typedef struct{
str name;
str surname;
int year;
int no;
}Student;
void list(Student[2],int sn);
int main() {
Student students[100] = {
{"samuel","any",20,111},
{"veronica","suqal",25,87}
};
int sl = 2;
puts("list, add, exit");
puts("------------------------\n");
str process;
while(strcmp(process,"exit")) {
gets(process);
if(!strcmp(process,"list")) list(students,sl);
else
if(!strcmp(process,"add")) {
sl++;
str name,surname,year,no;
printf("\n name: ");
gets(name);
printf("\n surname: ");
gets(surname);
printf("\n year: ");
gets(year);
printf("\n no: ");
gets(no);
strcpy(students[sl].name,name);
strcpy(students[sl].surname,surname);
students[sl].no = atoi(no);
students[sl].year = atoi(year);
printf("%s %d",name,atoi(no));
} else if(!strcmp(process,"exit")) {
puts("-------exiting--------");
}
else
{
str out = "not known command: ";
strcat(out,process);
puts(out);
}
}
return 0;
};
void list(Student* students,int sn) {
for(int i=0;i<sn;i++)
{
Student std = students[i];
printf("student: \n name: %s, surname: %s, years: %d, no: %d \n",std.name,std.surname,std.year,std.no);
}
};
当我添加一个新元素时,我可以使用 printf 在屏幕上读取它,但是当我使用函数列出它时,会发生这种情况:
list, add, exit
------------------------
add
name: hello
surname: world
year: 1
no: 1
hello 1
list
student:
name: samuel, surname: any, years: 20, no: 111
student:
name: veronica, surname: suqal, years: 25, no: 87
student:
name: , surname: , years: 0, no: 0
您应该在存储数据后立即增加“sl”。 这里,当你想添加第三个学生,但访问时,sl 等于 3 array[3] 给出数组的第四个值。