limerick2.c (2991B)
1 /* Exercise 8.12 */ 2 3 /* A bad implementation of the limerick generator */ 4 5 #include <stdio.h> 6 #include <string.h> 7 #include <stdlib.h> 8 #include <ctype.h> 9 #include <time.h> 10 11 #define LIMS 5 12 #define WORDS 8 /* Words for string (article, noun, etc.) */ 13 #define SIZE 90 14 15 char *strrpbrk(const char * const s, const char * const charset); 16 17 int main(void) 18 { 19 int i, j, k, x, l, rloop, rhymes[5] = { 0 }; 20 char tmp_s[SIZE], phrase[SIZE]; 21 const char matches[] = "aeiou", *tokp; 22 23 const char * const article = "the a one some any each no that"; 24 const char * const noun = "stupid girl guy town car dog cat day"; 25 const char * const verb = "drove looking ran walked skipped found seen borned"; 26 const char * const preposition = "to from over under on by in up"; 27 28 /* Store the memory address for each string */ 29 const char * const string[6] = { 30 article, noun, verb, 31 preposition, article, noun 32 }; 33 34 srand( time(NULL) ); 35 36 for(l = 0; l < LIMS; l++) { 37 38 /* loop the phrases */ 39 for(i = 0; i < 5; i++) { 40 41 /* loop the *string[] */ 42 for(j = 0; j < 6; j++) { 43 44 /* Create the phrase */ 45 rloop = 1 + rand() % WORDS; 46 47 for(k = 0; k < rloop && tokp != NULL; k++) { 48 if(!k) { 49 strcpy(tmp_s, string[j]); 50 tokp = strtok(tmp_s, " "); 51 } 52 else tokp = strtok(NULL, " "); 53 54 if(i && j == 5) { 55 /* Check the rhymes */ 56 for(x = 0; x < 5; x++) { 57 if(!x) { 58 strcpy(tmp_s, string[j]); 59 tokp = strtok(tmp_s, " "); 60 } 61 else tokp = strtok(NULL, " "); 62 63 /* set the rhymes */ 64 if(i == 1) { 65 if(*strrpbrk(tokp, matches) == rhymes[0]) { 66 break; 67 } 68 } 69 else if(i == 2) { 70 if(*strrpbrk(tokp, matches) != rhymes[0]) 71 break; 72 } 73 else if(i == 3) { 74 if(*strrpbrk(tokp, matches) == rhymes[2]) 75 break; 76 } 77 else if(i == 4) { 78 if(*strrpbrk(tokp, matches) == rhymes[0]) 79 break; 80 } 81 } 82 } 83 } 84 85 /* Append the token in the phrase */ 86 if(!j) 87 strcpy(phrase, tokp); 88 else 89 strcat(phrase, tokp); 90 strcat(phrase, " "); 91 } 92 rhymes[i] = *strrpbrk(phrase, matches); 93 strcat(phrase, "\0"); /* "Close" the string */ 94 95 /* Add some graphic stuff :-) */ 96 phrase[0] = toupper((int)phrase[0]); 97 phrase[strlen(phrase) - 1] = '.'; 98 99 printf("%2d: %s\n", i + 1, phrase); 100 101 } 102 103 printf("\n"); 104 105 } /* end for (l) */ 106 107 return 0; 108 } /* E0F main */ 109 110 /* The same of strbprk(3) except that the check 111 * is done from end to start of string pointer. */ 112 char * strrpbrk(const char * const s, const char * const charset) 113 { 114 int i; 115 char *ret; 116 117 for(i = strlen(s) - 1; i >= 0 ; i--) { 118 if( (ret = strchr(charset, s[i])) != NULL ) { 119 break; 120 } 121 } 122 123 return ret; 124 125 } /* eof strrbprk() */ 126