Home Segments Index Top Previous Next

540: Mainline

The following version of the analyze_trades program uses string, integer, and floating-point print specifications to display the neater report shown early in this chapter.

#include   
#include  
/* Define trade structure, industry enumeration, and arrays */ 
struct trade {double price; int number; char *description;}; 
enum {food = 'F', trucking = 'T', computers = 'C', 
      metals = 'M', health = 'H', airline = 'A'}; 
struct trade *trade_pointers[100]; 
char input_buffer[100]; 
/* Define auxiliary functions */ 
double trade_price (struct trade *x) { 
  return x -> price * x -> number; 
} 
char* industry_name (struct trade *t) { 
  switch (t -> description[0]) { 
    case food:          return "Food";        break; 
    // Other cases 
    default:            return "Unknown";     break; 
  } 
} 
char* company_name (struct trade *t) { 
  char* cptr = t -> description; 
  for (; cptr[0] != '-'; ++cptr) ; 
  return ++cptr; 
} 
main ( ) { 
  /* Declare various variables */ 
  int limit, counter, number; 
  double price, sum = 0.0; 
  /* Read trade information */ 
  for (limit = 0; 
       3 == scanf ("%s%lf%i", input_buffer, &price, &number); 
       ++limit) { 
    trade_pointers[limit]  
      = (struct trade*) malloc (sizeof (struct trade)); 
    trade_pointers[limit] -> price = price; 
    trade_pointers[limit] -> number = number; 
    trade_pointers[limit] -> description 
      = (char*) malloc (strlen (input_buffer) + 1); 
    strcpy (trade_pointers[limit] -> description, input_buffer); 
  } 
  /* Display report */ 
  for (counter = 0; counter < limit; ++counter)  
    printf ("%-10s %4s %5.1f %6i %9.0f\n", 
            industry_name(trade_pointers[counter]), 
            company_name(trade_pointers[counter]), 
            trade_pointers[counter] -> price, 
            trade_pointers[counter] -> number, 
            trade_price(trade_pointers[counter])); 
}