溫馨提示×

C語言項目:開發(fā)一個回文詩生成器

小樊
85
2024-04-26 17:25:52
欄目: 編程語言

#include <stdio.h> #include <string.h>

// Function to check if a string is palindrome int isPalindrome(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) { return 0; } } return 1; }

// Function to generate palindrome poem using input line void generatePalindromePoem(char *line) { // Split the line into words char *word = strtok(line, " “); while (word != NULL) { // Reverse the word and print it int len = strlen(word); for (int i = len - 1; i >= 0; i–) { printf(”%c", word[i]); } printf(" “); word = strtok(NULL, " “); } printf(”\n”); }

int main() { char line[100];

// Get input line from user
printf("Enter a line to generate palindrome poem: ");
fgets(line, sizeof(line), stdin);

// Remove newline character from input
line[strcspn(line, "\n")] = 0;

// Check if input line is palindrome
if (isPalindrome(line)) {
    // Generate palindrome poem
    generatePalindromePoem(line);
} else {
    printf("Input line is not a palindrome.\n");
}

return 0;

}

0