I have to compare the string "death" to to any five character string in a text file.
I can't seem to get my function to work but I can't see what I am doing wrong. Anyone have any suggestion?
*Notes: my strcmp returns only -1 or 1 but never 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;
}
As Havenard said, strcmp() requires null-terminated strings, which means each string needs to end with the character '\0'
. If you insist on piecing the strings together yourself, you have to remember to append that null character at the end of each one in order to perform string functions on them.