我正在尝试编写一个程序,检查输入到程序的单词是否与预定义的关键字之一匹配。输入将来自文本文件,文本文件将包含一个单词。到目前为止,我刚才的文本文件中有'青蛙'这个词,这意味着程序应该清楚地打印'找不到匹配',但它实际上会打印'匹配找到',即使当文本文件中的单词是一串随机字母。这是我的代码,是否有什么突出给你们?谢谢检查两个字符数组是否相等C
#define NUM 4
#define SIZE 12
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",
"feet"
};
//Removes non alphabetical characters
while((c = getchar()) != EOF && charCount <= 140) {
if(isAlpha(c)){
message[charCount] = c;
charCount++;
}
}
//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;
}
}
}
}
//prints "Match Found!" if there was a match
if (matchCheck == 1)
printf("Match Found!\n");
else
printf("No Match Found\n");
}
你不需要写'isAlpha',C已经有'isalpha'。 – Barmar
主要是我缺乏'strcmp()' – Notlikethat
当你发现不匹配的字符时,你永远不会退出你的循环。所以你要测试的是它们是否都以null结尾。但是,为什么你不使用'strcmp()'? – Barmar