1

私はここに来ていないのですか?

これはかなりうまく機能します:

for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
        found=strcmp( name, myContacts[i].cFirstName);
        printf(" i %d\n", i);
    }
printf(" \nName Found %s",  myContacts[i-1].cFirstName );

しかし、好奇心から、strstr()も使用しようとしています。

/*** This achieves the same functionality as above ***/

    for ( i = 0; i < 5  ;i++ ){
    found2=strstr( myContacts[i].cFirstName , name);
    printf(" i %d\n", i);
    if (found2 != NULL)
        {
        printf(" \nName Found %s",  myContacts[i].cFirstName );
        break;
        }
    }    

ただし、これは機能していません。

for ( i = 0; i < 5 && found2 != '\0' ;i++ ){ //this does not work as above
for ( i = 0; i < 5 && found2 != NULL ;i++ ){ // this also is not wroking
        found2=strstr( myContacts[i].cFirstName , name);
}

printf(" \nName Found %s",  myContacts[i].cFirstName );

よろしくお願いします。

完全なコード:

# please take my codes with a grain of skepticism, I am still learning 
# i know of sizeof(), but I rather not use it just for the purpose of my exercise

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXBUFFERSIZE   10

typedef struct contact {

    char cFirstName[10];
    char cLastName[10];
    char cTelphone[12];

} address ; // end type

// function prototype
void printContacts( address * );
void printMenu();
char getChoice();
void storeContact( address [] ,  int *);
//int searchContact( address [] , char * );
void searchContact( address [] , char [] );

int main(){

    char cSelection = 0;
    address myContacts[5];
    char buffer[MAXBUFFERSIZE];

    int i ;
    // initialize array to be zeros
    for ( i = 0; i < 5 ; i++ ){
        strcpy(myContacts[i].cFirstName, "0");
        strcpy(myContacts[i].cLastName,"0");
        strcpy(myContacts[i].cTelphone,"0"); 
    }

    strcpy(myContacts[0].cFirstName, "Jonny");
    strcpy(myContacts[1].cFirstName, "Julia");
    strcpy(myContacts[2].cFirstName, "Claudia");
    strcpy(myContacts[3].cFirstName, "Aaron");
    strcpy(myContacts[4].cFirstName, "Sebastian");

    int iDel = -1 ; // store the position if one deleted
    int iCount = 0 ; // counter for position in the array, when 
                     // inserting names.

    while ( cSelection != '5' ) {
    printMenu();
    cSelection = getChoice();

    switch (cSelection) {
        case '1':
            printContacts( myContacts );    
            break;

        case '2':
            if ( ( iDel >= -1 ) && ( iCount < 5 ) ){
                //printf("\niCount is %d ", iCount);
                storeContact( myContacts, &iCount );
                iCount++;
                //printf("\nOutside storeContact, *Plocation %d", iCount );
                }
            if ( iCount >= 5 ) {
                printf("\nThe Memory is full, consider deleting some"\
                "Contacts");    
                }
            break;

        case '3':
            {            
            printf("\nEnter a name or part of a name to search:\n");
            fscanf(stdin, "%s", buffer);
            getchar(); // clear the last enter
            printf("\nThe line you entered was:\n");
            printf("%s\n", buffer);
            searchContact( myContacts, buffer );
            break;
            }       
        case '4':   
            //iDel=deleteContact( myContacts );
            break;

        }// end of switch
    }// end of while
    return 0;
} // end main

char getChoice(){

    char cSelection = 'q'; //for the menu
    /**** always scanf CHARS so you can check
     *    if digit or char !!! ****/

    scanf("%s", &cSelection);

    while ( strlen(&cSelection) != 1 ){
        printf("\nChoich not understood, enter a number again:");
        scanf("%s",&cSelection);
        }

    if ( isalpha(cSelection) ){
        printf( "You entered a letter of the alphabet\n" );
        cSelection = -1;
        printf( "Illegal choice !!!" );
      }

    return cSelection;
    } 

void printContacts( address * myContacts ){

    int i ;

    for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 && i < 5 ; i++ ){                                             
        printf("\nmyContacts[%d].cFirstName: %s", i, \
        myContacts[i].cFirstName );
    }// end for
}

void printMenu(){
    printf("\n\n\tSilly Phone Book\n\n");
    printf("\n\n1\tPrint Phone Book\n");
    printf("2\tAdd New Contact\n");
    printf("3\tSearch For Contact\n");
    printf("4\tDelete Contact\n");
    printf("5\tQuit\n");
    printf("\nSelect Action: ");
    }

//void storeContact( address myContacts[] ){ //syntactic sugar
void storeContact( address * myContacts,  int *Plocation ){ 

    char ch;                     /* handles user input */
    char buffer[MAXBUFFERSIZE];  /* sufficient to handle one line */
    int x = 0;
    x=*Plocation;

    ch = getchar(); // clear the last enter
    printf("Enter a name (<10 characters)\n");
    //ch = getchar();
    //char_count = 0;
    //while( (ch != '\n')  && (ch != EOF ) &&  (char_count < MAXBUFFERSIZE)) {
        //buffer[char_count++] = ch;
        //ch = getchar();
    //}
    //buffer[char_count] = 0x00;      /* null terminate buffer */

    //fgets(buffer,11,stdin);

    fscanf(stdin, "%s", buffer); /* read from keyboard */

    printf("\nThe line you entered was:\n");
    printf("%s\n", buffer);

    //TODO: add check that string is not too long!!!
    // if we do that, the code won't blow here ?

    strcpy(myContacts[x].cFirstName, buffer);    
} 

//int searchContact( address * myContacts,    char name[] ){
void searchContact( address * myContacts,    char * name ){
    int found;
    char *found2;
    //printf("\nHey dude im buffer from inside searchContact: %s", name);
    // iterate throught the array, print possible matches
    int i = 0;


    //for ( i = 0; i < 5 && found != 0 ;i++ ){
    //for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
        //found=strcmp( name, myContacts[i].cFirstName);
        //printf(" i %d\n", i);
    //}
    //printf(" \nName Found %s",  myContacts[i-1].cFirstName );

    /*** This achieves the same functionality as above 

    for ( i = 0; i < 5  ;i++ ){
    found2=strstr( myContacts[i].cFirstName , name);
    printf(" i %d\n", i);
    if (found2 != NULL)
        {
        printf(" \nName Found %s",  myContacts[i].cFirstName );
        break;
        }
    }    ***/

    for ( i = 0; i < 5 && &found2 != '\0' ;i++ ){ //this does not work as above
        found2=strstr( myContacts[i].cFirstName , name);
        printf("found %p i %d\n", found2, i);
        //printf(" \nName Found %s",  myContacts[i].cFirstName );
    }

    //return found;
} // end of searchContacts  if ( isalpha(cSelection) ){
        printf( "You entered a letter of the alphabet\n" );
        cSelection = -1;
        printf( "Illegal choice !!!" );
      }

    return cSelection;
    } 

void printContacts( address * myContacts ){

    int i ;

    for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 && i < 5 ; i++ ){                                             
        printf("\nmyContacts[%d].cFirstName: %s", i, \
        myContacts[i].cFirstName );
    }// end for
}

void printMenu(){
    printf("\n\n\tSilly Phone Book\n\n");
    printf("\n\n1\tPrint Phone Book\n");
    printf("2\tAdd New Contact\n");
    printf("3\tSearch For Contact\n");
    printf("4\tDelete Contact\n");
    printf("5\tQuit\n");
    printf("\nSelect Action: ");
    }

//void storeContact( address myContacts[] ){ //syntactic sugar
void storeContact( address * myContacts,  int *Plocation ){ 

    char ch;                     /* handles user input */
    char buffer[MAXBUFFERSIZE];  /* sufficient to handle one line */
    int x = 0;
    x=*Plocation;

    ch = getchar(); // clear the last enter
    printf("Enter a name (<10 characters)\n");
    //ch = getchar();
    //char_count = 0;
    //while( (ch != '\n')  && (ch != EOF ) &&  (char_count < MAXBUFFERSIZE)) {
        //buffer[char_count++] = ch;
        //ch = getchar();
    //}
    //buffer[char_count] = 0x00;      /* null terminate buffer */

    //fgets(buffer,11,stdin);

    fscanf(stdin, "%s", buffer); /* read from keyboard */

    printf("\nThe line you entered was:\n");
    printf("%s\n", buffer);

    //TODO: add check that string is not too long!!!
    // if we do that, the code won't blow here ?

    strcpy(myContacts[x].cFirstName, buffer);    
} 

//int searchContact( address * myContacts,    char name[] ){
void searchContact( address * myContacts,    char * name ){
    int found;
    char *found2;
    //printf("\nHey dude im buffer from inside searchContact: %s", name);
    // iterate throught the array, print possible matches
    int i = 0;


    //for ( i = 0; i < 5 && found != 0 ;i++ ){
    //for ( i = 0; i < 5 && found != 0 ;++i ){ no difference than above
        //found=strcmp( name, myContacts[i].cFirstName);
        //printf(" i %d\n", i);
    //}
    //printf(" \nName Found %s",  myContacts[i-1].cFirstName );

    /*** This achieves the same functionality as above 

    for ( i = 0; i < 5  ;i++ ){
    found2=strstr( myContacts[i].cFirstName , name);
    printf(" i %d\n", i);
    if (found2 != NULL)
        {
        printf(" \nName Found %s",  myContacts[i].cFirstName );
        break;
        }
    }    ***/

    for ( i = 0; i < 5 && found2 != '\0' ;i++ ){ //this does not work as above
        found2=strstr( myContacts[i].cFirstName , name);
        printf("found %p i %d\n", found2, i);
        //printf(" \nName Found %s",  myContacts[i].cFirstName );
    }

    //return found;
} // end of searchContacts

この議論を完全にするために、私が望むように最終的に実際に機能したものを追加します。これはすべての答えを通過した後に来たので、みんなに感謝します:

ポインタを初期化するのを忘れました:

char *found2=NULL;

これで、次のループが期待どおりに機能します。

 for ( i = 0; i < 5 && !found2 ;i++ ){ //this does work as above

        found2=strstr( myContacts[i].cFirstName , name);
        printf("i %d\n", i);

    }
    printf("Name found %s", found2);

「Clau」を検索して「Claudia」と照合できるようになったので、strstr()でこの機能が必要でした。これはstrcmp()よりも私のニーズに適していますが、strcmp()でも実行できると確信しており、Cのスキルは私よりも洗練されています。

答えてくれてありがとう!

4

3 に答える 3

1

あなたfound2char *です。

あなたは書くべきですfor (i = 0; i < 5 && !found2; i++) //etc etc

found2(またはループ内でテストし、NULL以外の場合は中断します)

于 2011-12-19T20:57:52.307 に答える
1

サイクルは使用しないでください。strstr()を使用することにより、一度だけ使用する必要があります。

found2=strstr( myContacts[i].cFirstName , name);
printf(" \nName Found %s",  found2 );

(nullの対応するチェックを忘れないでください)

于 2011-12-19T20:58:25.240 に答える
1

forループ内の条件で:

&found2 != '\0'

自分自身についても言及しているように、found2がを指しているかどうかを確認したいので、それを作成します。それ以外の場合は、のアドレスをNUL文字( )と比較していますが、これは間違いなくあなたが望んでいることではありません。NULLfound2 != NULLfound2'\0'

strstrただし、スニペットがスニペットと同じ機能を持っていると言うのも間違っていますstrcmp。2つの機能は完全に異なります。のドキュメントをお読みくださいstrstr

もう1つ、最初のスニペット"Name Found"では常に印刷されます


また、コードには次のような多くの間違ったことがあります。

scanf("%s", &cSelection);
...
while ( strlen(&cSelection)

cSelectionをとして宣言します。charに格納するchar場合は、フォーマット指定子を使用します%c。文字列全体を読み取りたい場合は、char 配列&にします。配列のアドレスを関数に渡す場合は、これは不要です。

&cSelectionに渡されるのと同じ敵strlen。同じ理由で意味がありません。


(f)scanfまた、文字列の読み取りには安全ではなく、バッファオーバーフローを引き起こす可能性があるため、fgets(STRING, SIZE, stdin)代わりに使用する必要があります。とにかく、上記のすべてをキャッチできるように、コンパイラの警告を表示するだけです。

于 2011-12-19T21:08:58.410 に答える