Originally Posted by
sal817
I haven't learned the switch case yet, so not allowed to use in program
Oh? Phooey, I spent the last twenty minutes toying around with your program. Perhaps something like below will help anyway... just not today. At least you can test it for errors as I did not.
Code:
#include <stdio.h>
#include <string.h>
#define MAXB 10
const char *BOOKS[] = { "automobile", "cook", "gardening", "history",
"mystery", "planet", "science fiction", "self help",
"sports", "travel" };
int selectBook(void);
void printSck(int *);
int main(void)
{
char buf[BUFSIZ], *p;
int stockAmt[MAXB] = { 0 }; /* init stock */
int cIndex, sAmount;
while((cIndex = selectBook()) != 11)
{
cIndex -= 1;
printf("How many %s%s will Perfect Book carry: ",
BOOKS[cIndex], (cIndex == 1 ? "books" : " books"));
fgets(buf, sizeof buf, stdin);
if((p = strchr(buf, '\n')) != NULL)
*p = '\0';
if((sscanf(buf, "%d", &sAmount)) != 1)
fprintf(stderr, "Invalid amount detected - %s. Ignoring entry.\n\n", buf);
else
stockAmt[cIndex] = sAmount;
}
printSck(stockAmt);
puts("\nDone.\n");
while(getchar() != '\n'){}
return (0);
}
int selectBook(void)
{
char tmp[5];
int choice;
static char *message = "Please select a book below (1-11)\n\n"
" 1) Automobiles\n"
" 2) Cookbooks\n"
" 3) Gardening\n"
" 4) History\n"
" 5) Mystery\n"
" 6) Planets\n"
" 7) Science Fiction\n"
" 8) Self Help\n"
" 9) Sports\n"
"10) Travel\n"
"11) Exit Program\n\n-> ";
do
{
printf("%s", message);
fgets(tmp, sizeof tmp, stdin);
}while((sscanf(tmp, "%d", &choice)) != 1 || (choice < 1 || choice > 11));
puts("\n");
return (choice);
}
void printSck(int *tmp)
{
int i;
puts(" ---- Inventory ----\n");
for(i=0; i < MAXB; i++)
printf("%16s = %d\n", BOOKS[i], tmp[i]);
}