簡體   English   中英

在C中返回並打印字符串數組索引

[英]Returning and printing string array index in C

我有一個搜索名稱列表的函數,並且試圖獲取搜索函數以將數組的索引返回到主函數並打印出找到的名稱的起始位置。 到目前為止,我嘗試過的所有操作都使程序崩潰或導致奇怪的輸出。

這是我的搜索功能:

#include<stdio.h>
#include<conio.h>
#include<string.h>

#define MAX_NAMELENGTH 10
#define MAX_NAMES 5

void initialize(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys, int i);
int search(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys);

int main()
{
   char names[MAX_NAMES][MAX_NAMELENGTH];
   int i, Number_entrys,search_result,x;
   printf("How many names would you like to enter to the list?\n");
   scanf("%d",&Number_entrys);
   initialize(names,Number_entrys,i);
   search_result= search(names,Number_entrys);
   if (search_result==-1){
      printf("Found no names.\n");
   }else
   {
      printf("%s",search_result);
   }
   getch();
   return 0;
}

void initialize(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys,int i)
{
   if(Number_entrys>MAX_NAMES){
      printf("Please choose a smaller entry\n");
   }else{
      for (i=0; i<Number_entrys;i++){
         scanf("%s",names[i]);
      }
   }
}

int search(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys)
{
   int x;
   char new_name[MAX_NAMELENGTH];
   printf("Now enter a name in which you would like to search the list for\n");
   scanf("%s",new_name);

   for(x = 0; x < Number_entrys; x++) {
      if ( strcmp( new_name, names[x] ) == 0 )
      {
         return x;
      }
   } 
   return -1;        
}

就像我之前提到的那樣,我嘗試了許多不同的方法來嘗試解決此問題,但是我似乎無法使它們起作用。 像上面一樣打印X只是我嘗試的最后一件事,因此知道它不起作用。 關於最簡單的方法有什么建議嗎?

為什么不使用strcmp而不是strstr呢?

在您的代碼中,似乎存在一些巨大的問題:-似乎我使用的不是初始化。 -您將x聲明為int,然后使用:printf(“%s”,x)在這里有點廢話。 順便說一句不要初始化!

這樣的東西應該更好(請注意,我沒有您的initialize函數),並且我沒有嘗試編譯:

int search(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys)
{
   int x =0;
   char new_name[MAX_NAMELENGTH];
   printf("Now enter a name in which you would like to search the list for\n");
   scanf("%s",new_name);

   for(x = 0; x < Number_entrys; x++) 
   {
      if ( strcmp( new_name, names[x] ) == 0 )
      {
         return x;
      }
   } 
   return -1;        
 }

主要:

int main()
{
    char names[MAX_NAMES][MAX_NAMELENGTH];
    int i=0;
    int Number_entrys=0;
    int search_result=0;
    printf("How many names would you like to enter to the list?\n");
    scanf("%d",&Number_entrys);
    initialize(names,Number_entrys,i); // I guess it is use to initialize names ?!?
    search_result= search(names,Number_entrys);
    if (search_result==-1)
    {
         printf("Found no names.\n");
    }
    else
    {
       printf("Index found in position %d in the tab\n",search_result);
    }
   getch(); //not really a fan of this...
   return 0;
 }

希望能幫助到你。

問候,

約茲

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM