我正在尝试编写一个程序来检查输入到程序中的单词是否与预定义关键字之一匹配。输入将来自一个文本文件,文本文件中只有一个单词。到目前为止,我的文本文件只有“crackerjack”这个词,这意味着程序应该清楚地打印“找到匹配项”,但它目前没有这样做。这是我的代码,你们有什么突出的地方吗?谢谢
#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 个问题。其中两个已经得到解决:
确保 SIZE 足够大,可以在最长关键字的末尾包含一个
'\0'
确保文本文件在单词末尾包含
'\0'
。如果不是这种情况或超出您的控制范围,您始终可以在读取字符串后手动以'\0'
结尾。您在第二个
if
语句中缺少括号。这会导致每次输入第一个if
语句时执行break
语句。
关于在 C 中检查两个字符数组是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21441704/