/* * a more complicated program with function pointers * * Matt Bishop, ECS 36A * -- May 22, 2024 original version */ #include #include #include /* * first function: make everything upper case */ char *upper(char *str) { static char buf[1024]; /* buffer to return transformed string */ char *b; /* pointer to go through buf */ /* change all lower case letters to upper case */ for(b = buf; *str; b++, str++) *b = toupper(*str); /* return the internal. saved buffer */ return(buf); } /* * second function: make everything lower case */ char *lower(char *str) { static char buf[1024]; /* buffer to return transformed string */ char *b; /* pointer to go through buf */ /* change all upper case letters to lower case */ for(b = buf; *str; b++, str++) *b = tolower(*str); /* return the internal. saved buffer */ return(buf); } /* * the main function */ int main(void) { char inbuf[1024]; /* input buffer */ char *pin; /* used to scan the input buffer */ char *(*func)(char *); /* pointer to function to call */ /* * loop, transforming the input */ while(printf("l/u/EOF> "), fgets(inbuf, 1024, stdin) != NULL){ /* fgets keeps the newline; we don't want it */ if (inbuf[strlen(inbuf)-1] == '\n') inbuf[strlen(inbuf)-1] = '\0'; /* skip any leading white space */ pin = inbuf; while(isspace(*pin)) pin++; /* got a char -- interpret command */ /* note a NUL byte means nothing; */ /* go back and ask again */ switch(*pin++){ case '\0': /* NUL byte -- ignore line */ continue; case 'u': /* transform to upper case */ case 'U': func = upper; break; case 'l': /* transform to lower case */ case 'L': func = lower; break; default: /* remind the user of good commands */ printf("Commands: l, u, EOF\n"); continue; } /* now skip any intervening space */ while(isspace(*pin)) pin++; /* if there's no string, remind the user */ if (*pin == '\0'){ printf("input: [u | l] string or EOF\n"); continue; } /* do the transformation and print the result */ printf("'%s' becomes '%s'\n", pin, (*func)(pin)); } /* bye! */ return(0);}