【发布时间】:2016-02-22 00:18:32
【问题描述】:
您好,我正在尝试编写一个 C 程序,它基本上接受一个结构,将其存储在一个数组中,然后以这种格式打印该结构:
姓,名\n 等级:B
对于添加到数组中的每个项目,现在我遇到的问题是仅打印添加的最后一个项目。我知道这发生在 for 循环中,因为代码正在执行和打印。我不打算发布整个程序,因为它有很多代码,所以我只会放重要的部分。
void add(char* student_firstname, char* student_lastname, char* student_grade, char* student_level, struct student* list)
{
int i;
for (i = count-1; i < count; i++){
if ((strcmp(list[i].lastName, student_lastname) != 0) && (strcmp(list[i].firstName, student_firstname) != 0)){
strcpy(list[i].firstName, student_firstname);
strcpy(list[i].lastName, student_lastname);
strcpy(list[i].grade, student_grade);
}
else{
printf("This student is already on the list!");
}
//count++;
}
printf("Student added!");
}
count 变量之前设置为 0。 *不用担心 student_grade
display() 函数供参考:
void display()
{
int i;
for (i = count-1; i < count; i++){
printf("%s, %s \n", list[i].lastName, list[i].firstName);
printf("Grade: %s \n", list[i].grade);
}
}
这也是我的 read() 函数:
void read()
{
char student_firstName[100];
char student_lastName[100];
char student_grade[30];
char student_level[100];
printf("\nEnter the student's first name:\n");
fgets(student_firstName, sizeof(student_firstName), stdin);
printf("\nEnter the student's last name:\n");
fgets(student_lastName, sizeof(student_lastName), stdin);
printf("\nEnter the student's grade (A+,A,A-,...):\n");
fgets(student_grade, sizeof(student_grade), stdin);
printf("\nEnter the student's education level (f/so/j/s):\n");
fgets(student_level, sizeof(student_level), stdin);
// discard '\n' chars attached to input; NOTE: If you are using GCC, you may need to comment out these 4 lines
student_firstName[strlen(student_firstName) - 1] = '\0';
student_lastName[strlen(student_lastName) - 1] = '\0';
student_grade[strlen(student_grade) - 1] = '\0';
student_level[strlen(student_level) - 1] = '\0';
add(student_firstName, student_lastName, student_grade, student_level, list);
printf("\n"); // newline for formatting
}
【问题讨论】:
-
@MasterDNE -- 你的算法检查重复被破坏了,那是你的问题......