我具有此任务/功能来确定记录中是否已经存在学生的姓名/全名。 每个输入/条目中的学生姓名都不得相同。也没有重复的记录。
我的代码错误:
是当我输入5个学生姓名(例如:A,B,C,D,E)然后搜索D时,找不到返回值。因此,我想知道搜索每个元素是否存在的正确逻辑是什么?当我尝试A时,它说“已经存在”。
#include<stdio.h>
#include<string.h>
int main(){
char studentNames[50][50],names[50][50];
int i,studentcount;
printf("\nEnter number of students: ");
scanf("%d",&studentcount);
for(int i=0; i<studentcount; i++){
printf("\n[Student %d of %d]\n",i+1,studentcount);
printf("Enter name of student %d: \n",i+1);
scanf("%s", studentNames[i]);
}//this is the student record initialize.
/*assumed this is a function where it holds the data name to be searched
e.g
names[i]= "spiderman" then in studentNames[i]="venom",studentNames[i]="harley",studentNames[i]="octopops",
if i loop will it function like this?
the names[i]=spiderman compare to studentnames[i]=venom then if not equal iterate to harley and so on.
That's what I really want to do with my searching but I really dont know how to do it because of my poor logic thinking.
*/
for(int i=0; i<studentcount; i++){
printf("\nEnter Student's Name to be search: ");
scanf("%s",names[i]);
if (strcmp(studentNames[i],names[i]) == 0)
{
printf("Already exist.\n");
return 0;
}
printf("Not found\n");
return 1;
}
}
答案 0 :(得分:2)
您可能想要这样的东西:
char CompareStudent() {
printf("\nEnter Student's Name to be search: ");
char searchedname[100];
scanf("%99s", searchedname); // %99s instead of %s prevents buffer overflow
// (not very important at your level)
for (int i = 0; i < studentCount; i++) {
if (strcmp(studentNames[i], searchedname) == 0) {
printf("Already exists.\n");
return 0;
}
}
printf("Not found\n");
return 1;
}
这是带注释的原始原始代码:
char CompareStudent() {
printf("\nEnter Student's Name to be search: ");
for (int i = 0; i < studentCount; i++) {
scanf("%s", names[i]); // 1
if (strcmp(studentNames[i], names[i]) == 0)
{
printf("Already exist.\n");
return 0;
}
printf("Not found\n"); // 2
return 1;
}
}
问题: