1

I'm writing a program that is supposed to take in a list of names from the user, store them in an array, and then search through the list to check and see if the next name the user enters is part of the original list of names.

The issue I'm having is that when I go to enter a list of names, it only saves the last name entered into the list. Here is the part of code where I have problem:

#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 main()
{
    char names[MAX_NAMES][MAX_NAMELENGTH];

    initialize(names);
    getch();
    return 0;
}

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

    printf("How many names would you like to enter to the list?");
    scanf("%d",&Number_entrys);

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

    printf("%s",names); 
}
4

3 に答える 3

4

それは読むべきですscanf("%s",names[i]);

現在、あなたはそれを として保存しています scanf("%s",names);。これはと同等です scanf("%s",names[0]);

したがって、すべてのパスで同じ配列エントリを上書きしています。

編集: また、char names[][]関数に渡すと、最初の要素へのポインターのみが渡されます。宣言した値と同じ値に対して、少なくとも 1 つの境界を宣言する必要があります。

int main(){
    //To accept 2 names of 2 characters each
    char names[2][2];// or char** names;
    initialize(names, 2,2);
}
void initialize(char names[][2],const int MAX_NAMES,const int MAX_NAMELENGTH){ .. }
                             ^ syntax error if index not present

参考

于 2012-10-26T04:48:53.580 に答える
2

名前を配列の特定のエントリに保存する必要があります。

scanf("%s", names[i]);
printf("%s\n", names[i]);

また、いくつかの一般的な問題:

  • MAX_NAMES のような大文字の名前は、ほとんどの場合、変数ではなく定義に使用されます
  • scanf は、読み取りと書き込みの文字数を制限できないため、安全な関数ではありません。
于 2012-10-26T04:51:22.177 に答える
0

これまでのエントリを確認するには、 ( を読み込んだ後) から0までループし、それぞれを最新のものと照合する必要があります。i-1names[i]

文字列を比較するには、次を使用できますstrcmp

if( strcmp(names[i], names[j]) == 0 ) {
    /* Duplicate name - reboot universe */
}
于 2012-10-26T04:51:36.370 に答える