main.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
#include <stdio.h> #include <sys/time.h> #include <stdlib.h> #include <string.h> // Andy Fleischer - CS201 - Program #1 - 4/7/2021 // ---------------------------------------------- // This program shuffles the words in the sentence // "The quick brown fox jumps over the lazy dog" and // displays them one at a time for the user to type. // User is reprompted on misspellings, and after typing // all the words, their time taken is shown. int max(int a, int b); void shuffle(char* words[9]); void typing_game(char* words[9]); int main() { char* words[9] = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"}; shuffle(words); //setup random words printf("\nThis is a game that tests typing speed.\n"); printf("Press ENTER to start!\n"); getchar(); struct timeval start; struct timeval end; struct timeval total; gettimeofday(&start, NULL); typing_game(words); gettimeofday(&end, NULL); timersub(&end, &start, &total); //subtract starting time from finish time to give total printf("You took %ld seconds and %ld microseconds\n\n", total.tv_sec, total.tv_usec); return 0; } int max(int a, int b) //returns the greater of the two integers { return a > b ? a : b; } void shuffle(char* words[9]) //shuffles the set of words { //use gettimeofday to seed random struct timeval time; gettimeofday(&time, NULL); srand((time.tv_sec * 100) + (time.tv_usec / 100)); for (int i = 8; i > 0; i--) //Fisher-Yates shuffle { int j = rand() % (i+1); char* temp = words[i]; words[i] = words[j]; words[j] = temp; } } void typing_game(char* words[9]) //main game, user must type the given word { printf("Type the following words:\n"); char input[10]; char c; for (int i = 0; i < 9; i++) { do { printf("word #%d is %s: ", i+1, words[i]); if (scanf("%10s", input) > 0) ; while ((c = getchar()) != '\n' && c != EOF) ; //discard } while (strncmp(input, words[i], max(strlen(input), strlen(words[i]))) != 0); } } |