Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#define NUM_PORTS 6
#define NUM_PRODUCTS 9
typedef struct products {
char name[20];
int numberAvailable;
double unitPrice;
} products_p;
typedef struct{
char portName[10];
} ports_p;
void showPorts ( ports_p *ports, int numPorts ) {
int i;
for ( i = 0 ; i < numPorts ; i++ ) {
printf ( "%d : %s\n", i+1, ports[i].portName );
}
}
void showProducts ( products_p *products, int numProducts ) {
int i;
printf ( "Product Amount Price\n" );
for ( i = 0 ; i < numProducts ; i++ ) {
printf ( "%-20s %6d %4.2f\n",
products[i].name, products[i].numberAvailable, products[i].unitPrice );
}
}
int readIntFromUser ( const char *prompt ) {
char buff[BUFSIZ];
fputs ( prompt, stdout );
fflush ( stdout );
if ( fgets ( buff, BUFSIZ, stdin ) != NULL ) {
int result;
if ( sscanf ( buff, "%d", &result ) == 1 ) {
return result;
} else {
return 0;
}
} else {
return 0;
}
}
int purchase ( products_p *products, int numProducts, products_p *purchases ) {
int i;
int numPurchases = 0;
for ( i = 0 ; i < numProducts ; i++ ) {
int howMany;
printf ( "%s : %d available at %f each\n",
products[i].name, products[i].numberAvailable, products[i].unitPrice );
howMany = readIntFromUser ( "How many? > " );
if ( howMany > 0 && howMany <= products[i].numberAvailable ) {
/* reduce the port's amount by how many purchased */
products[i].numberAvailable -= howMany;
/* The number for us is how many we purchased */
purchases[numPurchases] = products[i];
purchases[numPurchases].numberAvailable = howMany;
numPurchases++;
}
}
return numPurchases;
}
int main( void ) {
ports_p ports[NUM_PORTS] = {
{ "Sydney" },
{ "London" },
{ "LosAngles" },
{ "NewYork" },
{ "Paris" },
{ "Tokyo" },
};
/* This should be on a per-port basis */
/* each port will have different products, at different prices */
products_p products[NUM_PRODUCTS] = {
{ { "Fish" }, 1, 11 },
{ { "Cotton" }, 2, 12 },
{ { "Wood" }, 3, 13 },
{ { "Coco" }, 4, 14 },
{ { "Sugar" }, 5, 15 },
{ { "Guns" }, 6, 16 },
{ { "Textiles" }, 7, 17 },
{ { "Tobacco" }, 8, 18 },
{ { "Wine" }, 9, 19 },
};
int choice;
showPorts ( ports, NUM_PORTS );
choice = readIntFromUser ( "Choose a port > " );
if ( choice >= 1 && choice <= NUM_PORTS ) {
products_p purchases[NUM_PRODUCTS]; /* The list of products we bought */
int numPurchases = 0; /* and how many products in all */
printf ( "The port has the following available\n" );
showProducts ( products, NUM_PRODUCTS );
numPurchases = purchase ( products, NUM_PRODUCTS, purchases );
printf ( "You purchased the following\n" );
showProducts ( purchases, numPurchases );
printf ( "The port has the following products left\n" );
showProducts ( products, NUM_PRODUCTS );
}
return 0;
}