// CSE 374 18sp Lecture 9 // Asks the user to input a string and an integer and echos the string // the requested number of times. // Demonstrates using the preprocessor (includes, defines), strings, // pointers, loops, and printf/scanf, as well as standard C file structure. // includes for functions & types defined in the standard libraries #include #include // symbolic constants #define MAX_ECHO_LENGTH 20 // global variables (if any) char prompt[] = "please enter a string and an integer\n"; // function prototypes (if not in a header file, to handle “declare before use”) int getInputs(int *numRepeatsPtr, char *str); void printRepeats(int numRepeats, char* str); // function definitions int main(int argc, char **argv) { int numRepeats; char str[MAX_ECHO_LENGTH + 1]; // Plus one for the null terminating character if (!getInputs(&numRepeats, str)) { return EXIT_FAILURE; // Defined in stdlib.h } printRepeats(numRepeats, str); return EXIT_SUCCESS; // Defined in stdlib.h } int getInputs(int *numRepeatsPtr, char *str) { int numInputs = 0; printf(prompt); while (numInputs < 2) { numInputs = scanf("%20s %d", str, numRepeatsPtr); if (numInputs < 2) { printf("bad input, needs string and integer\n"); numInputs = 0; } } if (!*numRepeatsPtr) { printf("cannot echo 0 times\n"); return 0; } return 1; } void printRepeats(int numRepeats, char* str) { for (int i = 0; i < numRepeats; i++) { printf("%s\n", str); } }