#include #include #include #include #include #include #include #define MAX_KEYS 256 #define MAX_MALLOC_VALUE 256 #define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ #define BOLDRED "\033[1m\033[31m" /* Bold RED */ #define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ #define RESET "\033[0m" typedef struct key_value { int key; char* value; } key_value; void print_key_values(key_value* kv, const int MAX); int find_key_index(key_value* kv, const char* STRING, const int MAX); int main(int argc, char *argv[]){ /* Seed time */ srand(time(NULL)); /* create key - value structure */ key_value* kv = malloc(sizeof(key_value) * MAX_KEYS); //returns void pointer. if (kv == NULL){ perror("Malloc failed"); exit(EXIT_FAILURE); } //read from file FILE* file; char* buf = (char*)malloc(MAX_MALLOC_VALUE * sizeof(char)); char* tmp = (char*)malloc(MAX_MALLOC_VALUE * sizeof(char)); char* tmp_value = (char*)malloc(MAX_MALLOC_VALUE * sizeof(char)); int number_of_items = 0; file = fopen("plu.csv", "r"); if(!file){ printf("Cannot open file\n"); exit(EXIT_FAILURE); } while(fgets(buf, MAX_MALLOC_VALUE, file) != NULL){ if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n')) buf[strlen (buf) - 1] = '\0'; tmp = strtok(buf, ","); tmp_value = strdup(tmp); //create copy of the value and store that in to tmp_value kv[number_of_items].value = tmp_value; strcpy(kv[number_of_items].value, tmp_value); //copy that value into the kv tmp = strtok(NULL, ","); kv[number_of_items].key = atoi(tmp); ++number_of_items; //keep count of items, helps us with generating random numbers } fclose(file); free(buf); // MAIN GAME LOOP char line[256]; int input; int score = 0; system("clear"); printf(BOLDYELLOW "CTRL-D to leave the PLU test\n" RESET); while(1){ int random = rand() % number_of_items; //generate a random number with the number of items char* item_to_guess = kv[random].value; int code_to_guess = kv[find_key_index(kv, item_to_guess, number_of_items)].key; printf("[%d]--> %s: ", score, item_to_guess); if (fgets(line, sizeof(line), stdin) && input != EOF) { if (sscanf(line, "%d", &input) == 1) { if(input == code_to_guess){ printf(BOLDGREEN "✓ Correct!\n" RESET); ++score; } else { printf(BOLDRED "✗ Nope! It's: %d\n" RESET, code_to_guess); } } else { printf(BOLDYELLOW "\nOnly whole number integers can be entered, Sorry!\n" RESET); continue; } sleep(2); system("clear"); } else { printf(BOLDYELLOW "\n\nYour score was %d\nBye!" RESET, score); exit(EXIT_SUCCESS); } } /* free memory! */ free(kv); free(tmp); free(tmp_value); return EXIT_SUCCESS; } void print_key_values(key_value* kv, const int MAX){ printf("| %20s | %4s |\n", "Value", "Key"); printf("| -------------------- | ---- |\n"); for(int i = 0; i < MAX; i++){ printf("| %20s | %4d |\n", kv[i].value, kv[i].key); } } int find_key_index(key_value* kv, const char* STRING, const int MAX){ int i = 0; //index while(strcmp(STRING, kv[i].value)){ ++i; if(i > MAX){ i = -1; break; } } return i; }