0

私のコードはこれです。私はファイルを読んでいて、ファイル内のデータからユーザーが入力した単語を比較してから、ファイルから次の2つの単語を印刷したいと思っています。どうやってやるの?

        #include <stdio.h>
        #include <string.h>
        int main()
        {
           //Open the file for reading
                    FILE *in = fopen("data.txt", "r");
           char str[]="file1.txt";
           //fgets buffer
           char buffer[100];

         //Pieces of string tokenized
        char * stringPiece;

         //int for comparing strings
           int compare=2;


        //While loop. Getting lines from file
        while ( fgets(buffer, sizeof(buffer), in) != NULL ){
             fgets(buffer, 100, in);
            // printf("%s\n", buffer);

         stringPiece = strtok (buffer,",");
             while (stringPiece != NULL){


          printf("%s\n",stringPiece);
          compare=strcmp(stringPiece,str);

          if (compare==0){printf("HELP");}

          //printf("%s\n",stringPiece);
          stringPiece = strtok (NULL, " ");
      }
   }
         //Close file
                fclose(in);

                       return 0;
}

ユーザーが入力したものと同じファイル内の単語を見つけることができますが、ファイルから次の2つの単語を印刷できません。ファイル名はdata.txtです。

読みやすいようにフォーマットされたコード(ほとんどの場合、関数のオープンブレースで使用vimします)。=%main()

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

int main(void)
{
    //Open the file for reading
    FILE *in = fopen("data.txt", "r");
    char str[]="file1.txt";
    //fgets buffer
    char buffer[100];

    //Pieces of string tokenized
    char * stringPiece;

    //int for comparing strings
    int compare=2;

    //While loop. Getting lines from file
    while ( fgets(buffer, sizeof(buffer), in) != NULL ){
        fgets(buffer, 100, in);
        // printf("%s\n", buffer);

        stringPiece = strtok (buffer,",");
        while (stringPiece != NULL){

            printf("%s\n",stringPiece);
            compare=strcmp(stringPiece,str);

            if (compare==0){printf("HELP");}

            //printf("%s\n",stringPiece);
            stringPiece = strtok (NULL, " ");
        }
    }
    //Close file
    fclose(in);

    return 0;
}
4

1 に答える 1

0

単語を検索し、次の2つの単語を取得するサンプル

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

int main() {
    char userInputWord[]="file1.txt";
    char readFromFileData[]="c:,file1.txt,date,size";
    char *tokenPtr,*nextFirstWord,*nextSecondWord;

    tokenPtr=strtok(readFromFileData, ",");
    for(;tokenPtr != NULL;tokenPtr=strtok(NULL, ",")){
        if(0!=strcmp(tokenPtr, userInputWord))
            continue;//skip word
        //find it!
        printf("%s\n",tokenPtr);
        nextFirstWord = strtok(NULL, ",");
        nextSecondWord = strtok(NULL, ",");
        if(nextFirstWord)
            printf("first word is \"%s\"\n", nextFirstWord);
        else
            fprintf(stderr,"first word is nothing!\n");
        if(nextSecondWord)
            printf("second word is \"%s\"\n", nextSecondWord);
        else
            fprintf(stderr,"second word is nothing!\n");
    }
    return 0;
}
于 2012-05-19T20:18:17.590 に答える