簡體   English   中英

在C中檢查兩個字符數組是否相等

[英]Checking two character arrays for equality in C

我正在嘗試編寫一個程序,以檢查輸入到程序中的單詞是否與預定義關鍵字之一匹配。 輸入將來自文本文件,文本文件中將只有一個單詞。 到目前為止,我剛剛在文本文件中使用了“ crackerjack”一詞,這意味着程序應該清楚地打印“ Match Found”,但目前尚未這樣做。 這是我的代碼,對您來說有什么特別的嗎? 謝謝

#define NUM 4
#define SIZE 11

int isAlpha(char);

//Returns 1 if it is an Alphabetical character, 0 if it is not
int isAlpha(char c) {
  return (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z');
}

int main() {
  char message[141];
  int charCount = 0, c = 0, matchCheck = 0;

  char keywords[NUM][SIZE] = {
    "crackerjack",
    "Hey",
    "dog",
    "fish"
  };

  //Removes non alphabetical characters
  while((c = getchar()) != EOF && charCount <= 140) {
    if(isAlpha(c)){
      message[charCount] = c;
      charCount++;
    }
    printf("%d", isAlpha(c));
  }

  //checks if message matches keyword
  for (int i = 0; i < NUM; i++) {
    for (int j = 0; j < SIZE; j++) {

      //Check if current two characters match
      if (message[j] == keywords[i][j]) {
        //Check if the two matched characters are the null terminator character
    if (message[j] == '\0' && keywords[i][j] == '\0')
          matchCheck = 1;
          break;
      } 
      //if characters are not the same, break from loop
      else {
        break;
      }  
    } 
  }


  //prints "Match Found!" if there was a match
  if (matchCheck == 1) {
    printf("Match Found!\n");
}

}

您的代碼中有3個問題。 其中兩個已經解決:

  1. 確保SIZE足夠大,以便在最長關鍵字的末尾包含'\\0'

  2. 確保文本文件在單詞末尾包含'\\0' 如果不是這種情況,或者超出您的控制范圍,則在讀取字符串后,始終可以將其以'\\0'結束。

  3. 您在第二個if語句中缺少方括號。 這導致break語句在每次輸入第一個if語句時執行。

SIZE太小。 '\\0'騰出空間。

#define SIZE 12
char keywords[NUM][SIZE] = {
  "crackerjack",
  ...
};

我現在看到這實際上是@ user3121023所說的。 歸功於@ user3121023。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM