Reputation: 9
I am trying to write a program that checks to see if a word inputed to a program matches one of the predefined keywords. Input is going to be coming from a text file and the text file will have a single word in it. So far the text file I have just has the word 'crackerjack' which means the program should clearly print 'Match Found' but it is not currently doing that. Here is my code, does anything stand out to you guys? Thanks
#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");
}
}
Upvotes: 0
Views: 292
Reputation: 236
There are 3 problems in your code. Two of them have already been addressed:
Ensure that SIZE is big enough to include a '\0'
at the end of the longest keyword
Ensure that the text file includes a '\0'
at the end of the word. If it is not the case or it is out of your control, you can always manually end the string with a '\0'
after reading it.
You are missing brackets on your second if
statement. This causes the break
statement to be executed every time the first if
statement is entered.
Upvotes: 2
Reputation: 154243
SIZE
is too small. Make room for '\0'
.
#define SIZE 12
char keywords[NUM][SIZE] = {
"crackerjack",
...
};
I see now this is effectively what @user3121023 said. Credit to @user3121023.
Upvotes: 1