mkphrase.c (1393B)
1 /* Exercise 8.11 */ 2 3 #include <stdio.h> 4 #include <string.h> 5 #include <stdlib.h> 6 #include <ctype.h> 7 #include <time.h> 8 9 #define PHRASES 20 10 #define SIZE 30 11 12 int main(void) 13 { 14 int i, j, k; 15 char tmp_s[SIZE], phrase[SIZE]; 16 const char * tokp; 17 18 const char * const article = "the a one some any"; 19 const char * const noun = "boy girl do town car"; 20 const char * const verb = "drove jumped ran walked skipped"; 21 const char * const preposition = "to from over under on"; 22 23 /* Store the memory address for each string */ 24 const char * const string[6] = { 25 article, noun, verb, 26 preposition, article, noun 27 }; 28 29 srand( time(NULL) ); 30 31 /* loop the phrases */ 32 for(i = 0; i < PHRASES; i++) { 33 34 /* loop the *string[] */ 35 for(j = 0; j < 6; j++) { 36 37 /* Copy the string and tokenize it */ 38 strcpy(tmp_s, string[j]); 39 tokp = strtok(tmp_s, " "); 40 for(k = rand() % 5; k && tokp != NULL; k--) 41 tokp = strtok(NULL, " "); 42 43 /* Append the token in the phrase */ 44 if(!j) 45 strcpy(phrase, tokp); 46 else { 47 strcat(phrase, tokp); 48 } 49 strcat(phrase, " "); 50 } 51 strcat(phrase, "\0"); /* "Close" the string */ 52 53 /* Add some graphic stuff :-) */ 54 phrase[0] = toupper((int)phrase[0]); 55 phrase[strlen(phrase) - 1] = '.'; 56 57 printf("Phrase %2d: %s\n", i+1, phrase); 58 59 } 60 61 return 0; 62 } /* E0F main */ 63