/* * Program to check whether string is a palindrome. * Also illustrates using fgets to get a line of text, and strcmp to * compare strings. * With a command-line argument of "test", runs the function for some * predefined tests. Otherwise prompts for a line of text. */ #include #include #include #include bool is_palindrome(char *s); void testit(char *s); int main(int argc, char *argv[]) { if ((argc > 1) && (strcmp(argv[1], "test") == 0)) { testit("aba"); testit(""); testit("abBA"); testit("abcd"); testit("A man, a plan, a canal -- Panama!"); return 0; } char line[100]; puts("enter a line of text"); fgets(line, sizeof line, stdin); char *eol = strchr(line, '\n'); if (eol == NULL) { puts("line too long"); } else { *eol = '\0'; printf("%s a palindrome\n", is_palindrome(line) ? "is" : "is not"); } return 0; } void testit(char *s) { printf("'%s' %s a palindrome\n", s, is_palindrome(s) ? "is" : "is not"); } bool is_palindrome(char *s) { char *p = s; char *q = s + strlen(s) - 1; while (p < q) { while (!isalpha(*p)) ++p; while (!isalpha(*q)) --q; if ((p < q) && (tolower(*p) != tolower(*q))) return false; ++p; --q; } return true; }