[英]How can I search array of names in an element of an array
我有這個任務/功能來確定學生的姓名/完整姓名是否已存在於記錄中。 每個輸入/條目中的學生姓名都不應該相同。 也沒有記錄中的條目重復。
我的代碼的錯誤:
是不是當我輸入 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;
}
}
你可能想要這樣的東西:
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;
}
}
問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.