0

文字列「death」を、テキスト ファイル内の任意の 5 文字の文字列と比較する必要があります。

関数が機能しているようには見えませんが、何が間違っているのかわかりません。誰にも何か提案はありますか?

*注意: 私の strcmp は -1 または 1 のみを返し、0 は決して返しません

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

//Function to check if strings are a match regardless of case
bool doesMatch (char testText[], char testDeath[]) {
 if (strcasecmp(testDeath, testText) == 0) {
      return true;
 }
 else
      return false;
}

int main (int argc, char *argv[]) {
 char test1[5] = {getchar(), getchar(), getchar(), getchar(), getchar()};
 bool testMatch;
 char test2[5] = {'d','e','a','t','h'};

 //Test arrays until End of FIle
 while (test1[4] != EOF) {

      testMatch = doesMatch(test1, test2);
      if (testMatch == true) {
           printf ("Match!\n");
      }

      //"slide" array down one character
      test1[0] = test1[1];
      test1[1] = test1[2];
      test1[2] = test1[3];
      test1[3] = test1[4];
      test1[4] = getchar();

 }

 return 0;
}
4

3 に答える 3

4

Havenard が言ったように、strcmp() は null で終わる文字列を必要とします。つまり、各文字列は文字で終わる必要があります'\0'。自分で文字列をつなぎ合わせる必要がある場合は、文字列関数を実行するために、各文字列の最後にヌル文字を追加することを忘れないでください。

于 2013-04-05T01:43:18.123 に答える
1

への引数はstrcmp、NUL で終了する必要があります。現在のコードに対する最も簡単な変更は、配列の長さを 5 文字ではなく 6 文字にし、6 文字目を 0 または '\0' で初期化することです。または、strncasecmp長さ 5 で呼び出すこともできます。これにより、配列の 6 番目の文字にアクセスするという未定義の動作も回避されます。

于 2013-04-05T01:42:50.033 に答える
0

'\0'入力の終了を省略する正当な理由があると仮定すると、strncasecmp()代わりに次を使用できます。

bool doesMatch (char testText[], char testDeath[], size_t n) {
     return strncasecmp(testDeath, testText, n) == 0;
}

/*...*/
    testMatch = doesMatch(test1, test2, 5);
于 2013-04-05T01:45:25.950 に答える