/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when adding an item succeeds and false when it does not **/ BOOLEAN add_item(struct ppd_system * system) { struct ppd_stock * item; int len, rc, gen_id = ppd_stock_generate_id(); item = (struct ppd_stock*) malloc(sizeof(struct ppd_stock)); if(item == NULL){ perror("malloc"); return FALSE; } bzero(item, sizeof(struct ppd_stock)); sprintf(item->id, "I%04i", gen_id); printf("This new meal item will have the Item id of I%i.\n", gen_id); printf("Enter the item name:"); if((fgets(item->name, NAMELEN, stdin) == NULL) || (item->name[0] == '\n')){ return FALSE; } len = strlen(item->name); if(item->name[len-1] != '\n'){ /* If we have more data to read*/ read_rest_of_line(); }else{ item->name[len-1] = '\0'; } printf("Enter the item description:"); if((fgets(item->desc, DESCLEN, stdin) == NULL) || (item->desc[0] == '\n')){ return FALSE; } len = strlen(item->desc); if(item->desc[len-1] != '\n'){ /* If we have more data to read*/ read_rest_of_line(); }else{ item->desc[len-1] = '\0'; } printf("Enter the price for this item:"); rc = fscanf(stdin, "%u.%u", &item->price.dollars, &item->price.cents); if((rc == EOF) || (rc != 2)){ return FALSE; } read_rest_of_line(); /* read the newline and everything else*/ item->on_hand = DEFAULT_STOCK_LEVEL; if(ppd_stock_list_insert(system, item) == 0){ printf("This item \"%s-%s\" has now been added to the menu.\n", item->name, item->desc); return TRUE; } return FALSE; }
int get_string(char* string, unsigned length) { int finished = FALSE; char tempString[30]; do { fgets(tempString, length + 2, stdin); if (tempString[strlen(tempString) - 1] != '\n') { printf("Input was too long.\n"); read_rest_of_line(); } else { finished = TRUE; } } while (finished == FALSE); tempString[strlen(tempString) - 1] = '\0'; strcpy(string, tempString); return TRUE; }
/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when removing an item succeeds and false when it does not **/ BOOLEAN remove_item(struct ppd_system * system) { struct ppd_stock * item; int len; char item_id[IDLEN+1]={0}; printf("Please enter the id of the item to remove from the menu:"); if((fgets(item_id, sizeof(item_id), stdin) == NULL) || (item_id[0] == '\n')){ return FALSE; } len = strlen(item_id); if(item_id[len-1] != '\n'){ /* If we have more data to read*/ read_rest_of_line(); }else{ item_id[len-1] = '\0'; } item = ppd_find_stock_id(system->item_list, item_id); if(item == NULL){ fprintf(stderr, "Error: Item with id %s not found.\n", item_id); return FALSE; } if(item->on_hand <= 0){ printf("You have selected \"%s\", but there are no items of that kind on hand.\n", item->name); return FALSE; } printf("\"%s - %s\" has been removed from the system.\n", item->id, item->desc); ppd_stock_list_remove(system, item); return TRUE; }
int read_input() { char input[SELECTION_SIZE + 2]; int done = 0; int choice = 0; int char_conversion = 48; //difference between char '1' and int 1 do { printf("\nInput: "); fgets(input, SELECTION_SIZE + 2, stdin); if(input[strlen(input)-1] != '\n') { printf("Error: Input was too long. \n"); read_rest_of_line(); } else { input[strlen(input)-1] = '\0'; done = 1; } } while(done != 1); //Converts numeric char to int choice = input[0]-char_conversion; return choice; }
BOOLEAN get_int_in_range(int lower, int higher, int *output) { char input[MAX_INT_INPUT], *endPtr = NULL; BOOLEAN inputSuccess = FALSE; while(!inputSuccess) { if(fgets(input, MAX_INT_INPUT, stdin) == NULL) { return FALSE; } if(input[0] == '\n') { return FALSE; } if(input[strlen(input)-1] != '\n') { printf("Error: input too long\n"); printf("Please enter a interger between %d and %d\n", lower, higher); read_rest_of_line(); continue; } input[strlen(input) -1] = '\0'; *output = (int)strtol(input, &endPtr, 10); if(strcmp(endPtr, "") == 0) { if(*output < lower || *output > higher) { printf("Error: The value you entered was not in the required range\n"); printf("Please enter a interger between %d and %d\n", lower, higher); continue; } else { inputSuccess = TRUE; } } } return TRUE; }
enum input_result get_player_column(int *column_choice) { char user_input[INPUT_LEN + EXTRACHARS]; char* stringcheck = NULL; /* Accept input */ fgets(user_input, INPUT_LEN + EXTRACHARS, stdin); /* Checks if user entered a blank input */ if(user_input[1] == '\0') { return RTM; } /* A string that doesn't have a newline character is too long */ else if(user_input[strlen(user_input) - 1] != '\n') { fprintf(stderr, "Error: Input was too long\n"); read_rest_of_line(); return FAILURE; } else { /* Converts user input into a long int */ *column_choice = strtol(user_input, &stringcheck, BASE10); /* Checks if there is any character after integer input */ if(*stringcheck == '\n') { /* Checks if the column choice is within the board boundaries */ if(*column_choice >= MINCOLUMN && *column_choice <= MAXCOLUMN) { *column_choice -= DECREMENTBY1; return SUCCESS; } /* Prints error if selection is outside board boundaries */ else { fprintf(stderr, "Error: Invalid column selection\n"); return FAILURE; } /* Prints error if characters where found in the input */ } else { fprintf(stderr, "Error: Invalid input!\n"); return FAILURE; } } }
/*handle user input */ void user_input(char * input) { fgets(input, MAX_INPUT_LEN+EXTRASPACES,stdin); /*check for buffer overflow */ if(input[strlen(input)-1]!='\n') { printf("Error: buffer overflow, input may have exceeded the maximum" " char length (20)\n"); read_rest_of_line(); return; } /*remove newline */ input[strlen(input)-1]= '\0'; }
/************************************************************************** * ascii_to_binary() - implements the "ASCII to Binary Generator" option * (requirement 3) from the main menu. Essentially, you need to implement * an algorithm for conversion of integers to binary and apply this to * every character in the input array (called 'ascii' here) and print out * the result. Finally, you need to update the option_stats array * appropriately **************************************************************************/ void ascii_to_binary(int * option_stats, char * ascii) { int count = 0; int convertedAscii[ASCII_LENGTH] = {0}; clearScreen(); printf("\nASCII to Binary Generator\n"); printf("---------------------------\n\n"); printf("Enter a string (1-5 characters): "); while(fgets(ascii, ASCII_LENGTH + EXTRA_SPACES, stdin) != NULL){ if (ascii[strlen(ascii) - 1] != '\n'){ printf("Error: Input was too long! Please try again.\n"); read_rest_of_line(); } else if (strcmp(ascii, "\n") == 0){ return; } else{ ascii[strlen(ascii) - 1] = '\0'; } printf("\nBinary representation: "); for (count = 0; count < strlen(ascii); count++){ convertedAscii[count] = ascii[count]; printf("%i ", decimaltobinary(convertedAscii[count])); } printf("\n"); option_stats[OPTION_2]+=1; return; } }
/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when removing an item succeeds and false when it does not **/ BOOLEAN remove_item(struct ppd_system * system) { char input[IDLEN + EXTRA_CHARS]; BOOLEAN inputSuccess = FALSE; /** * Loop until ID in correct format is found, and the ID is found in the * linked list. **/ printf("Press crtl + d or enter on a new line at any time to cancel.\n"); printf("Please enter the ID of the item you wish to delete: "); while(!inputSuccess) { if(fgets(input, IDLEN + EXTRA_CHARS, stdin) == NULL) { printf("Returning to the menu.\n"); return FALSE; } if (input[0] == '\n') { printf("Returning to the menu.\n"); return FALSE; } else if(input[strlen(input)-1] != '\n') { printf("Error: input to long.\n"); printf("Please enter the letter 'I' followed by 4 digits: "); read_rest_of_line(); continue; } if(input[0] != 'I') { printf("Error: incorrect ID format\n"); printf("Please enter the letter 'I' followed by 4 digits: "); continue; } input[strlen(input)-1] = '\0'; if(list_delete_node(system->item_list, input) == FALSE) { printf("Please enter an existing ID: "); continue; } else { printf("Success! returning to the menu\n"); return TRUE; } } return FALSE; }
BOOLEAN get_input(char * input, int length) { fgets(input, length + EXTRACHARS, stdin); if(input[1] == '\0') { return TRUE; } if(input[strlen(input) - 1] != '\n') { read_rest_of_line(); fprintf(stderr, "Error: line entered was too long. " "Please try again\n"); return FALSE; } input[strlen(input) - 1] = 0; return TRUE; }
/*Function for getting a string from user input. * Written by Steven Burrows, 2006 ([email protected]). */ int getString(char* string, unsigned length, char* prompt) { int finished = FALSE; char tempString[TEMP_STRING_LENGTH + 2]; /* Continue to interact with the user until the input is valid. */ do { /* Provide a custom prompt. */ printf("%s", prompt); /* Accept input. "+2" is for the \n and \0 characters. */ fgets(tempString, length + 2, stdin); /* A string that doesn't have a newline character is too long. */ if (tempString[strlen(tempString) - 1] != '\n') { printf("Input was too long.\n"); read_rest_of_line(); } else { finished = TRUE; } } while (finished == FALSE); /* Overwrite the \n character with \0. */ tempString[strlen(tempString) - 1] = '\0'; /* Make the result string available to calling function. */ strcpy(string, tempString); /*Return false if the string is empty*/ if(string[0] == '\0') return FALSE; else return TRUE; }
/*Reference from lecture sample code @getIntger-basic.c */ int get_integer(int *integer, int length, int min, int max) { int finished = FALSE; char tempString[30]; int tempInteger = 0; char* endPtr; do { fgets(tempString, length + 2, stdin); if (tempString[strlen(tempString) - 1] != '\n') { printf("Input was too long.\n"); read_rest_of_line(); } else { tempString[strlen(tempString) - 1] = '\0'; tempInteger = (int) strtol(tempString, &endPtr, 10); if (strcmp(endPtr, "") != 0) { printf("Input was not numeric.\n"); } else if (tempInteger < min || tempInteger > max) { printf("Input was not within range %d - %d.\n", min, max); } else { finished = TRUE; } } } while (finished == FALSE); *integer = tempInteger; return TRUE; }
enum input_result getPlayerName(char* name) { int finished = FALSE; char tempString[NAMELEN + EXTRACHARS] = ""; /* Get name of player */ do { printf("What is your name?\n"); fgets(tempString, NAMELEN + EXTRACHARS, stdin); if(tempString[1] == '\0') { return RTM; } /* A string that doesn't have a newline character is too long */ else if (tempString[strlen(tempString) - 1] != '\n') { fprintf(stderr, "Error: Input was too long\n"); read_rest_of_line(); } else { finished = TRUE; } }while (finished != TRUE); /* Overwrite the \n character with \0 */ tempString[strlen(tempString)-1] = '\0'; /* Makes result available to calling function */ strcpy(name, tempString); return SUCCESS; }
/*************************************************************************** * add_ticket() - Request user input about creating a new ticket type in * the system. You need to validate this input and then create and insert * a new ticket into the system, sorted by ticket name. this option * implements requirement 6 in the assignment 2 specifications. **************************************************************************/ void add_ticket(tm_type * tm) { struct stock_data *data = NULL; char temp_ticket_name[TICKET_NAME_LEN], temp_ticket_type[1 + EXTRA_SPACES], temp_ticket_zone[TICKET_ZONE_LEN+1]; char char_ticket_price[10]; unsigned int temp_ticket_price = 0; BOOLEAN finished = FALSE; char * prompt1 = "Ticket name (1-40 characters): "; char * prompt2 = "Ticket type (1 character): "; char * prompt3 = "Ticket zone (1-3 characters): "; printf("\nAdd Ticket\n"); printf("-----------\n\n"); if (stringinput(prompt1, temp_ticket_name, TICKET_NAME_LEN) == FALSE){ return; } if (charinput(prompt2, temp_ticket_type, 1 + EXTRA_SPACES) == FALSE){ return; } if (zoneinput(prompt3, temp_ticket_zone, TICKET_TYPE_LEN + EXTRA_SPACES) == FALSE){ return; } /*Input cents*/ do{ printf("Price (in cents): "); fgets(char_ticket_price, 10, stdin); if(char_ticket_price[strlen(char_ticket_price) -1] !='\n'){ printf("Error: Input was too long! Try again.\n"); read_rest_of_line(); } else if (strcmp(char_ticket_price, "\n") == 0){ return; } else{ char_ticket_price[strlen(char_ticket_price) -1] = '\0'; temp_ticket_price = atoi(char_ticket_price); finished = TRUE; } } while (!finished); /*Malloc stock_data*/ data = (struct stock_data *)malloc(sizeof(struct stock_data)); /*If memory allocation fails*/ if (!data){ perror("Error: Memory allocation failed! Exiting...\n"); free(data); exit(EXIT_FAILURE); } /*Add temp variables to struct*/ strcpy(data -> ticket_name, temp_ticket_name); data ->ticket_type = *temp_ticket_type; strcpy(data -> ticket_zone, temp_ticket_zone); data -> ticket_price = temp_ticket_price; data -> stock_level = DEFAULT_STOCK_LEVEL; /*Send data to add stock function*/ add_stock_to_node(tm, data); printf("Ticket successfully added to system.\n"); }
/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when a purchase succeeds and false when it does not **/ BOOLEAN purchase_item(struct ppd_system * system) { char buf[IDLEN+1]={0}; struct price left, give; struct ppd_stock * item; int len, refund; printf("Purchase Item:\n"); printf("-------------\n"); printf("Please enter the id of the item you wish to purchase:"); if((fgets(buf, sizeof(buf), stdin) == NULL) || (buf[0] =='\n')){ return FALSE; } len = strlen(buf); if(buf[len-1] != '\n'){ /* If we have more data to read*/ read_rest_of_line(); }else{ buf[len-1] = '\0'; } item = ppd_find_stock_id(system->item_list, buf); if(item == NULL){ fprintf(stderr, "Error: Item with id %s not found.\n", buf); return FALSE; } if(item->on_hand <= 0){ printf("You have selected \"%s\", but we are out of stock.\n", item->name); return FALSE; } printf("You have selected \"%s\". This will cost you $%i.%02i\n", item->desc, item->price.dollars, item->price.cents); printf("Please hand over the money – type in the value of each note/coin in cents.\n"); printf("Press enter or ctrld on a new line to cancel this purchase:\n"); left = item->price; refund = 0; while((left.dollars > 0) || (left.cents > 0)){ int coins; printf("You still need to give us $%i.%i:", left.dollars, left.cents); if((fgets(buf, sizeof(buf), stdin) == NULL) || (buf[0] =='\n')){ /*Ctrl-D or Enter*/ refund = 1; break; } len = strlen(buf); if(buf[len-1] != '\n'){ /* If we have more data to read*/ read_rest_of_line(); }else{ buf[len-1] = '\0'; } coins = 0; if(sscanf(buf, "%i", &coins) != 1){ perror("scanf"); continue; } if(ppd_is_denom(coins) == 1){ printf("Error: $%i.%02i is not a valid denomination of money.\n", coins/100, coins%100); continue; } ppd_add_coins(system, coins); give.dollars = coins / 100; give.cents = coins % 100; if(give.dollars > 0){ if(give.dollars >= left.dollars){ give.dollars -= left.dollars; left.dollars = 0; }else{ left.dollars -= give.dollars; } } if(give.cents > 0){ if(give.cents >= left.cents){ give.cents -= left.cents; left.cents = 0; }else{ left.cents -= give.cents; } } } if(refund){ struct price coins_back; coins_back.dollars = item->price.dollars - left.dollars; coins_back.cents = item->price.cents - left.cents; printf("You are being refunded with $%i,%i: ", coins_back.dollars, coins_back.cents); ppd_return_change(system, &coins_back); /* refund */ printf("\n"); return FALSE; /* return to main menu */ } item->on_hand--; printf("Thank you. Here is your %s", item->name); if(give.dollars > 0 || give.cents > 0){ printf(", and your change of $ %i.%i: ", give.dollars, give.cents); ppd_return_change(system, &give); }else{ printf("."); } printf("\nPlease come again soon.\n"); return TRUE; }
int main(int argc, char * argv[]) { int i; char chosen[CHOICE_DIGITS]; struct vm vm; struct menu_item menu_items[NUM_MENU_ITEMS]; BOOLEAN quit = FALSE, check_load; if( argc != NUMARGS ) { fprintf( stderr, "Incorrect number of command line arguments. \n" ); return EXIT_FAILURE; } vm.foodfile = argv[1]; vm.coinsfile = argv[2]; if( vm_init( &vm ) == OS_SAID_FO ) { perror( "Failed to allocate memory for list" ); return EXIT_FAILURE; } check_load = load_data( &vm, argv[1], argv[2] ); if( check_load != TRUE ) { if( check_load == OS_SAID_FO ) { perror( "Failed to load items or money" ); } return EXIT_FAILURE; } /* If load_data did not scan the next_id from file */ if( strcmp( vm.next_id, "I0000" ) == 0 ) { set_next_id( &vm, 0 ); } menu_init( menu_items ); while( !quit ) { printf( "\nMain Menu: \n" ); for( i=1; i<=NUM_MENU_ITEMS; ++i ) { printf( "%d. %s \n", i, menu_items[i-1].name ); if( i == ADMIN_ONLY_AFTER ) { printf( "Administrator Only Menu \n" ); } } printf( "Select your option (1 - %d): ", NUM_MENU_ITEMS ); fgets( chosen, CHOICE_DIGITS, stdin ); printf( "\n" ); read_rest_of_line(); i = (int) strtol( chosen, NULL, 10 ); /* * Note that i is used for re-use of variables. It could be called * "choice" */ if( !( i>=1 && i<=NUM_MENU_ITEMS ) ) { printf( "A valid option was not chosen. Please try again." "\n" ); } else { if( menu_items[i-1].func( &vm ) == OS_SAID_FO ) { perror( "Failed to allocate memory for new item or new" " list node" ); return EXIT_FAILURE; } if( menu_items[i-1].func == save || menu_items[i-1].func == abort_the_fucking_program ) { quit = TRUE; } } } return EXIT_SUCCESS; }
/************************************************************************** * matching_brackets() - implements the "Matching Brackets" option * (requirement 4) from the main menu. You need to implement an algorithm * which will parse a string passed in and determine whether the brackets * all match, including the type of brackets. You need to account for * {} [] () and you also need to allow for the nesting of brackets. * You need to tell the user whether the brackets match or not. Finally you * need to update the option_stats array appropriately. **************************************************************************/ void matching_brackets(int * option_stats, char * test_string) { int i = 0, j = 0, stackelem = 0, mismatch = 0; char brackets[TEST_STRING_LENGTH] = {0}; tos = stack; p1 = stack; clearScreen(); printf("Matching Brackets\n"); printf("-----------------\n\n"); printf("Enter a string (1-20 characters): "); while(fgets(test_string, TEST_STRING_LENGTH + EXTRA_SPACES, stdin) != NULL){ if (test_string[strlen(test_string) - 1] != '\n'){ printf("Error: Input was too long! Please try again.\n"); read_rest_of_line(); } else if (strcmp(test_string, "\n") == 0){ return; } else{ test_string[strlen(test_string) - 1] = '\0'; } for (i = 0; test_string[i] != '\0'; i++){ if (test_string[i] == '('){ stackelem = 1; strcat(brackets, "("); push(stackelem); } else if (test_string[i] == ')'){ strcat(brackets, ")"); if (pop() == -1){ printf("Brackets do not match.\n"); return; } } else if (test_string[i] == '{'){ stackelem = 2; strcat(brackets, "{"); push(stackelem); } else if (test_string[i] == '}'){ strcat(brackets, "}"); if (pop() == -1){ printf("Brackets do not match.\n"); return; } } else if (test_string[i] == '['){ stackelem = 3; strcat(brackets, "["); push(stackelem); } else if (test_string[i] == ']'){ strcat(brackets, "]"); if (pop() == -1){ printf("Brackets do not match.\n"); return; } } } for (j = 0; j < sizeof(stack)/sizeof(int); j++){ if (stack[j] == 1 || stack[j] == 2 || stack[j] == 3){ printf("Brackets do not match.\n"); mismatch = 1; break; } } if (mismatch == 1){ return; } printf("Brackets match!\n"); option_stats[OPTION_3]+=1; return; } }
/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when a purchase succeeds and false when it does not **/ BOOLEAN purchase_item(struct ppd_system * system) { char idInput[IDLEN + EXTRA_CHARS], costInput[PRICELEN + EXTRA_CHARS], denomName[PRICE_VALUE_LEN], **endPtr = NULL; int i, j, dollarsToPay, centsToPay, totalToPay = 0, moneyInserted = 0, change = 0, moneyForCashReg[NUM_DENOMS], moneyForChange[NUM_DENOMS]; enum denomination registerArrayPos; enum denomination_cent_value centValue; BOOLEAN inputSuccess = FALSE, hasChange = FALSE, hasInsertedMoney = FALSE; /** * memset the arrays uses to track money inserted and change to give, to * avoid leftover data in memory giving unexpected values. **/ memset(moneyForCashReg, 0, sizeof(moneyForCashReg)); memset(moneyForChange, 0, sizeof(moneyForChange)); /** * The while loop which prompts user for the ID of the item they wish to * purchase **/ printf("Please enter the ID of the item you would like to purchase: "); while(!inputSuccess) { if(fgets(idInput, IDLEN + EXTRA_CHARS, stdin) == NULL) { printf("Returning to the menu.\n"); return FALSE; } if (idInput[0] == '\n') { printf("Returning to the menu.\n"); return FALSE; } else if(idInput[strlen(idInput)-1] != '\n') { printf("Error: input to long.\n"); printf("Please enter the letter 'I' followed by 4 digits: "); read_rest_of_line(); continue; } if(idInput[0] != 'I') { printf("Error: incorrect ID format\n"); printf("Please enter the letter 'I' followed by 4 digits: "); continue; } idInput[strlen(idInput)-1] = '\0'; if(item_search(system->item_list, idInput, &dollarsToPay, ¢sToPay) == FALSE) { printf("Please enter an existing ID: "); continue; } inputSuccess = TRUE; } inputSuccess = FALSE; printf("Please hand over: $%d.%.2d \n", dollarsToPay, centsToPay); printf("Maximum denomination accepted is: 10 dollars (1000 cents)"); printf(" at a time.\n"); printf("Press crtl + d or enter on a new line at any time to cancel.\n"); printf("Please enter the value of each note/coin in cents: "); totalToPay = ((dollarsToPay * 100) + centsToPay); /** * The loop which promts the user to input the money needed to purchase the * item. **/ while(totalToPay != 0) { if(fgets(costInput, PRICELEN + EXTRA_CHARS, stdin) == NULL) { printf("Returning to Menu.\n"); if(hasInsertedMoney) { refund_money(moneyForCashReg); } return FALSE; } if(costInput[0] == '\n') { printf("Returning to menu.\n"); if(hasInsertedMoney) { printf("Refunding Money Inserted: "); refund_money(moneyForCashReg); } return FALSE; } if(costInput[strlen(costInput)-1] != '\n') { printf("Error: input too long\n"); printf("Please enter an ID less than %d characters long", PRICELEN); read_rest_of_line(); continue; } /** * Checks if money inserted is a valid coin/note. If it is, adds the * coin/note to the array, and continues depending on whether money * is still owed or not **/ moneyInserted = (int)strtol(costInput, endPtr, 10); switch(moneyInserted) { case CENT_FIVE_CENTS: case CENT_TEN_CENTS: case CENT_TWENTY_CENTS: case CENT_FIFTY_CENTS: case CENT_ONE_DOLLAR: case CENT_TWO_DOLLARS: case CENT_FIVE_DOLLARS: case CENT_TEN_DOLLARS: if(moneyInserted % CENT_FIVE_CENTS == 0) { if(moneyInserted < totalToPay) { registerArrayPos = id_to_denom(moneyInserted); ++moneyForCashReg[registerArrayPos]; totalToPay -= moneyInserted; hasInsertedMoney = TRUE; printf("You still owe: %d cents.\n", totalToPay); printf("Please insert more money: "); continue; } else if(moneyInserted == totalToPay) { registerArrayPos = id_to_denom(moneyInserted); ++moneyForCashReg[registerArrayPos]; moneyInserted = 0; totalToPay = 0; change = 0; hasInsertedMoney = TRUE; break; } else if(moneyInserted > totalToPay) { registerArrayPos = id_to_denom(moneyInserted); ++moneyForCashReg[registerArrayPos]; moneyInserted -= totalToPay; change = moneyInserted; hasChange = TRUE; hasInsertedMoney = TRUE; totalToPay = 0; break; } } else { printf("Sorry, that is not a recognised Australian Currency\n"); printf("Please enter a valid note/coin in cents: "); } } if(totalToPay == 0) { break; } printf("Sorry, that is not a recognised Australian Currency\n"); printf("Please enter a valid note/coin in cents: \n"); } /** * Cycles through the change value, starting from the highest denomination, * and adds change to the array if it can, otherwise goes to the next lowest * denomination. If there is still change left after this process, the * register does not have enough money to give change, the transaction is * cancelled, and the money inserted is refunded. **/ if(change != 0) { for(i = NUM_DENOMS-1; i >= 0; --i) { if(change == 0) { break; } centValue = denom_to_ID(i); if(change >= centValue) { if((change / centValue) > system->cash_register[i].count) { /* go to next lower denomination */ moneyForChange[i] += system->cash_register[i].count; continue; } moneyForChange[i] = change / centValue; change = change % centValue; } } if(change != 0) { printf("Error: Not enough change to proccess sale.\n"); printf("Refunding money inserted: "); if(hasInsertedMoney) { printf("Refunding Money Inserted: "); refund_money(moneyForCashReg); } printf("Returning to Menu.\n\n"); return FALSE; } } /** * If the system cannot dispense the item, money is refunded and the user * is returned to the menu **/ printf("\n"); if(item_purchase(system, idInput) == FALSE) { if(hasInsertedMoney) { printf("Refunding Money Inserted: "); refund_money(moneyForCashReg); } printf("Returning to menu.\n\n"); return FALSE; } /** * Adds the money inserted to the systems cash register and deducts the * change given from the register. **/ for(i = 0; i < NUM_DENOMS; ++i) { system->cash_register[i].count += moneyForCashReg[i]; system->cash_register[i].count -= moneyForChange[i]; } /** * If change was needed to be given, this prints out the the change in the * specified format. **/ if(hasChange) { printf("Thank you. Here is your item, and your change of %d.%02d: ", moneyInserted/100, moneyInserted % 100); for(i= NUM_DENOMS-1; i >= 0; --i) { if(moneyForChange[i] != 0) { switch(i) { case FIVE_CENTS: strcpy(denomName, "5c"); break; case TEN_CENTS: strcpy(denomName, "10c"); break; case TWENTY_CENTS: strcpy(denomName, "20c"); break; case FIFTY_CENTS: strcpy(denomName, "50c"); break; case ONE_DOLLAR: strcpy(denomName, "$1"); break; case TWO_DOLLARS: strcpy(denomName, "$2"); break; case FIVE_DOLLARS: strcpy(denomName, "$5"); break; case TEN_DOLLARS: strcpy(denomName, "$10"); break; default: printf("Error: out of array bounds\n"); printf("Returning to menu.\n\n"); return FALSE; } for(j = moneyForChange[i]; j > 0; --j) { printf("%s ", denomName); } } } } printf("\n\n"); return TRUE; }
/** * @param system a pointer to a ppd_system struct that contains * all the information for managing the system. * @return true when adding an item succeeds and false when it does not **/ BOOLEAN add_item(struct ppd_system * system) { char idInput[IDLEN + EXTRA_CHARS], nameInput[NAMELEN + EXTRA_CHARS], descInput[DESCLEN + EXTRA_CHARS], priceInput[PRICELEN + EXTRA_CHARS]; char *token, **endPtr = NULL; int dollarsToSave, centsToSave, idToIncrement; BOOLEAN inputSuccess = FALSE; struct ppd_node *current; struct ppd_stock search; current = system->item_list->head; memset(&search, 0, sizeof(struct ppd_stock)); strcpy(search.id, current->data->id); /** * Small loop to find the highest id and copies it. **/ while(current != NULL) { if(item_cmp_id(current->data, &search) > 0) { strcpy(search.id, current->data->id); } current = current->next; } /** * Retrieves the number from the highest id and increments it by 1. **/ token = strtok(search.id, ID_DELIM); idToIncrement = (int)strtol(token, endPtr, 10); ++idToIncrement; /** * Checks the ID, and for up to a maximum of 9999 ID's in the linked list, * adds the correct amount of 0's to the front, depending on its size. **/ if(idToIncrement < 10) { sprintf(idInput, "I000%d", idToIncrement); printf("The new ID for your product is: %s\n", idInput); } else if(idToIncrement < 100) { sprintf(idInput, "I00%d", idToIncrement); printf("The new ID for your product is: %s\n", idInput); } else if(idToIncrement < 1000) { sprintf(idInput, "I0%d", idToIncrement); printf("The new ID for your product is: %s\n", idInput); } else if(idToIncrement <= 9999) { sprintf(idInput, "I%d", idToIncrement); printf("The new ID for your product is: %s\n", idInput); } else { printf("Error: can only have a total of 9999 items in the list\n"); printf("Returning to menu\n"); return FALSE; } token = NULL; /** * Loop until a name has been entered correctly. **/ printf("Please enter the name of the item: "); printf("Press crtl + d or enter on a new line at any time to cancel.\n"); while(!inputSuccess) { if(fgets(nameInput, NAMELEN + EXTRA_CHARS, stdin) == NULL) { printf("Returning to menu\n"); return FALSE; } if(nameInput[0] == '\n') { printf("Returning to menu.\n"); return FALSE; } if(nameInput[strlen(nameInput)-1] != '\n') { printf("Error: input too long\n"); printf("Please enter a name less than %d characters long", NAMELEN); read_rest_of_line(); continue; } nameInput[strlen(nameInput)-1] = '\0'; inputSuccess = TRUE; } inputSuccess = FALSE; /** * Loop until a description has been entered correctly. **/ printf("Please enter a description of the item you are adding: "); while(!inputSuccess) { if(fgets(descInput, DESCLEN + EXTRA_CHARS, stdin) == NULL) { printf("Returning to menu\n"); return FALSE; } if(descInput[0] == '\n') { printf("Returning to menu.\n"); return FALSE; } if(descInput[strlen(descInput)-1] != '\n') { printf("Error: input too long\n"); printf("Please enter a description less than %d", DESCLEN); printf(" characters long"); read_rest_of_line(); continue; } descInput[strlen(descInput)-1] = '\0'; inputSuccess = TRUE; } inputSuccess = FALSE; token = NULL; endPtr = NULL; /** * Loop until a price that can be made up by Australian currency, and is * less than $100. **/ printf("The price of an item must be less than $100, seperated by a '.', "); printf("and two digits must be entered for the cents value.\n"); printf("Please enter the price of the item you are adding: "); while(!inputSuccess) { if(fgets(priceInput, PRICELEN + EXTRA_CHARS, stdin) == NULL) { printf("Returning to menu\n"); return FALSE; } if(priceInput[0] == '\n') { printf("Returning to menu.\n"); return FALSE; } if(priceInput[strlen(priceInput)-1] != '\n') { printf("Error: input too long\n"); printf("Please enter a name less than %d long", PRICELEN); read_rest_of_line(); continue; } token = strtok(priceInput, CURRENCY_DELIM); dollarsToSave = (int)strtol(token, endPtr, 10); if(strlen(token) > 2) { printf("Error: price must be less than $100\n"); printf("Please enter a price less than $100\n"); continue; } token = strtok(NULL, CURRENCY_DELIM); centsToSave = (int)strtol(token, endPtr, 10); if(strlen(token) != 3 || (centsToSave % CENT_FIVE_CENTS) != 0) { printf("Error: You must enter exatly two digits for cents.\n"); printf("Eg: 20.00, or 9.60\n"); printf("Please enter a price less than $100 that conforms to "); printf("these standards\n"); continue; } inputSuccess = TRUE; } /** * Allocate the memory for the new node, now that all information has been * gathered. **/ current = malloc(sizeof(struct ppd_node)); current->data = malloc(sizeof(struct ppd_stock)); if(current == NULL || current->data == NULL) { printf("The memory alocation failed\n"); printf("Returning to menu\n"); free(current->data); free(current); return FALSE; } /** * Copy information into the node, **/ current->next = NULL; strcpy(current->data->id, idInput); strcpy(current->data->name, nameInput); strcpy(current->data->desc, descInput); current->data->price.dollars = dollarsToSave; current->data->price.cents = centsToSave; current->data->on_hand = DEFAULT_STOCK_LEVEL; /** * Pass the node to the list_add_system function, check for problems, * free memory if adding fails. **/ if(list_add_node(system->item_list, current) == FALSE) { printf("The node failed to load\n"); printf("This was not meant to happen\n"); free(current->data); free(current); return FALSE; } printf("New item: %s|%s|%s|%d.%d|%d\n", idInput, nameInput, descInput, dollarsToSave, centsToSave, DEFAULT_STOCK_LEVEL); printf("has been successfully added!\n"); return TRUE; }
/************************************************************************** * format_text() - implements the "Formatting Text" option (requirement 6) * from the main menu. You will need to parse the text, adding newlines * so that no line is longer than "width" which means you will need to * replace the first white space character before this with the newline. You * then need to insert extra spaces so that lines are spaced as evenly as * possible. Finally you want to update the option_stats array appropriately. * **************************************************************************/ void format_text(int * option_stats, unsigned width, char * text) { BOOLEAN finished = FALSE; char input[TEXT_INT_INPUT + EXTRA_SPACES]; int wordcount = 0; int col = 0, i; char * wordPtr; clearScreen(); printf("\nFormatting Text\n"); printf("------------------\n\n"); do{ printf("Enter an integer (maximum number of chars per line): "); fgets(input, TEXT_INT_INPUT + EXTRA_SPACES, stdin); if (input[strlen(input) - 1] != '\n'){ printf("Error: Input was too long! Please try again.\n"); read_rest_of_line(); } else if (strcmp(input, "\n") == 0){ return; } else{ input[strlen(input) - 1] = '\0'; /*convert input to an int, and store in width variable*/ width = atoi(input); finished = TRUE; } } while(!finished); finished = FALSE; do{ printf("Enter some sentences (between 150 - 200 chars): "); fgets(text, TEXT_LENGTH + EXTRA_SPACES, stdin); if (text[strlen(text) - 1] != '\n'){ printf("Error: Input was too long! Please try again.\n"); read_rest_of_line(); } else if (strcmp(text, "\n") == 0){ return; } else if (strlen(text) < 150){ printf("Error: Input was too short! Please enter between 150 and 200 characters.\n"); read_rest_of_line(); } else{ text[strlen(text) - 1] = '\0'; finished = TRUE; } } while(!finished); /*process text using the number entered*/ printf("\nFormatted Text:\n"); wordPtr = strtok(text, " "); while (wordPtr != NULL){ for (i = 0; i <= strlen(wordPtr); i++){ col++; printf("%c", wordPtr[i]); if (i == strlen(wordPtr)){ printf(" "); } if (col == width){ printf("\n"); col = 0; } } wordcount++; wordPtr = strtok(NULL, " "); } printf("\nWord count: %i\n", wordcount); printf("\n"); option_stats[OPTION_4]+=1; }
/************************************************************************** * perfect_squares() - implements the "Perfect Squares" option (requirement * 2) from the main menu. You need to determine whether the number passed * in is a perfect square and let the user know if it is or not. You also * need to print the perfect square before and after this value. Finally * you need to update the option_stats variable appropriately. **************************************************************************/ void perfect_squares(int * option_stats, unsigned number) { char charNumber[SQUARENUMBERINPUT + EXTRA_SPACES]; int square, roundup, rounddown; double result; clearScreen(); printf("\nPerfect Squares\n"); printf("------------------\n\n"); printf("Enter a positive integer (1-100000): "); /*!=NULL is the test for ctrl-D*/ while (fgets(charNumber, SQUARENUMBERINPUT + EXTRA_SPACES, stdin) != NULL){ if (charNumber[strlen(charNumber) - 1] != '\n'){ printf("Error: Input was too long! Please try again.\n"); read_rest_of_line(); } else if (strcmp(charNumber, "\n") == 0){ return; } else if ((number = atoi(charNumber)) < 0){ printf("Error: Number is a negative! Please try again.\n"); read_rest_of_line(); } else{ charNumber[strlen(charNumber) - 1] = '\0'; number = atoi(charNumber); } for (square = 0; square <= number; square++){ if (number == square * square){ printf("%u is a perfect square.\n", number); printf("Perfect square before: %i\n", (square - 1) * (square - 1)); printf("Perfect square after: %i\n", (square + 1) * (square + 1)); return; } } printf("%u is not a perfect square.\n", number); result = sqrt(number); roundup = (int)(result + 1); rounddown = (int)(result); printf("Perfect square before: %i\n", rounddown*rounddown); printf("Perfect square after: %i\n", roundup*roundup); option_stats[OPTION_1]+=1; return; } }