I am making a program to track how long it takes a user to complete a task.
Everything works relatively fine, but I get a warning on a line and I'm not sure why: "Implicit declaration of function 'timersub' is invalid in C99"
The use of timersub in test(), works, I just don't understand the warning. I thought timersub was covered in time.h.
Here is my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
struct timeval start, stop, res;
void welcome();
void randomize (char *arr[], int n);
void swap (char **a, char **b);
double test (char *arr[], int n);
//Main function
int main()
{
char *arr[] = {
"The",
"quick",
"brown",
"fox",
"jumps",
"over",
"the",
"lazy",
"dog"
};
int n = sizeof(arr)/sizeof(arr[0]); //Get total words in array.
randomize(arr,n); //Pass array to randomizer.
welcome();
double timer = test(arr,n);
printf("Test took %f seconds to complete.\n", timer);
return 0;
}
//Function to display the welcome message.
void welcome()
{
printf("Welcome to the Typing Speed Test.\n");
printf("You will be given a random permutation of words to type.\n");
printf("The timer will begin when the first word appears.\n");
printf("You will not be able to move on to the next word until you\n");
printf("correctly spell the word provided.\n");
printf("Press ENTER to begin.\n");
getchar();
}
//Function to randomize the words in an array.
void randomize(char **arr, int n) {
gettimeofday(&start,NULL);
unsigned long time_ms = 1000000 * start.tv_sec + start.tv_usec;
srand(time_ms);
for (int i = n-1; i > 0; --i){
int j = rand()%(i+1);
swap (&arr[i], &arr[j]);
}
}
//Function to swap two pointers in an array.
void swap (char **a, char**b)
{
char *temp=*a;
*a=*b;
*b=temp;
}
//Function to run the typing test.
double test(char *arr[], int n)
{
char str1[20];
int correct;
gettimeofday(&start, NULL);
for (int i = 0; i < n; ++i){
do{
printf("Word number %d: %s\n", i+1, arr[i]);
scanf("%10s", str1);
if(strcmp(arr[i], str1) != 0){
printf("Incorrect.\n");
correct = 0;
}
else{
correct = 1;
}
} while (correct == 0);
}
gettimeofday(&stop, NULL);
timersub(&start, &stop, &res);
return res.tv_sec + res.tv_usec/1000000.0;
}
Any suggestions?