0

1行のファイルがあります.Linuxでは、デフォルトで改行で終わります

one two three four

そして、同様のもの

one five six four

間にある 2 つの単語が「4」にならないことが保証されています。このコードのように、「ツー スリー」と「ファイブ シックス」を変数に代入したいので、次のように書きました。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool getwords(FILE *example)
{
    bool result = 0;
    char *words;
        if(fscanf(example, "one %s four\n", words) == 1)
        {
            printf("captured words are %s\n", words);
            if(words == "two three"
            || words == "five six")
            {
                puts("example words found");
            }
            else
            {
                puts("unexpected words found");
            }
            result = 1; //so that we know this succeeded, in some way
        }
    return result;
}

int main(int argc, char * argv[])
{
    if(argc != 2)
    {
        exit(0);
    }
    FILE *example;
    example = fopen(argv[1],"r");
    printf("%x\n", getwords(example)); //we want to know the return value, hex is okay
    fclose(example);
    return 0;
}

問題は、これが "captured words are " を出力し、2 つの単語のうち最初の単語だけが文字列として期待されることです。これは、単語「one」と「four」の間に 2 より多くの単語が存在する可能性があるファイルをサポートすることになっています。コードを変更して、文字列内の最初の単語と最後の単語の間のすべての単語を取得するにはどうすればよいですか?

4

2 に答える 2

1

現在の状態では、コードに多数のエラーがあります。

まず、割り当てる必要がありますchar *words;このステートメントは現在、文字列へのポインターを宣言するだけで、文字列を作成しません。簡単な修正はchar words[121];.

また、scanf のキャプチャ範囲をwordswithの長さと一致するように制限しscanf("one %120s four", words);ます。%sただし、これは1 つの単語のみを検索するため、2 つの単語をキャプチャしません。解決策は、各単語をスキャンしてからfscanf("one %120s %120s four", first_word, second_word);、1 つずつ比較することです。

==次に、演算子を使用して 2 つの文字列を比較することはできません。==変数の値を比較し、words単なるポインターです。修正はstrcmp(words, "two three") == 0、あなたが書いた場所を使用することですwords == "two three"

于 2013-08-08T02:19:24.693 に答える