Here's my succinct version. Thanks for the tips dwks.
Code:
#include <stdio.h>
#define STORE_NAME "Sierra Sporting Goods"
void add_report() {
printf("Report added\n") ;
return ;
}
void report() {
printf("Report run\n") ;
return ;
}
void delete_record() {
printf("record deleted\n") ;
return ;
}
void change_record() {
printf("record changed\n") ;
return ;
}
int scanf_ok(int chars_read, int max, int * choice ) {
if (chars_read == EOF || chars_read == 0 ) return 0 ;
if (*choice < 1 || *choice > max) return 0 ;
return 1 ;
}
int main(void) {
int response = 0;
int chars_read ;
int i ;
struct {
const char *text ;
void (*function)() ;
} item[] = {
{ "Add a Report" ,add_report } ,
{ "Report" ,report } ,
{ "Delete a record",delete_record } ,
{ "Change a record",change_record } ,
{ "Quit" ,0 }
} ;
while ( 1 ) {
// Present the menu of options.
printf("\t%s\n\n", STORE_NAME) ;
for (i = 0 ; i < ( sizeof(item) / sizeof(*item)) ; i++) {
printf("%d = %s\n", i+1, item[i].text ) ;
}
// Read the response and validate it and process it
if ( scanf_ok( scanf("%d", &response), sizeof(item) / sizeof(*item) , &response ) ) {
if (item[response-1].function == 0) break ;
else item[response-1].function() ;
}
// else, tell user to try again.
else {
printf("Invalid or Non numeric value entered. Try again.\n") ;
while ( ( chars_read=getchar() ) != '\n' && chars_read != EOF) ; /* clear buffer */
}
} // while 1
return 0;
}
Any tips for improvement?