I implemented a C program where you enter a sequence of numbers separated with a space like 1 2 3 4 5
. The program sees that the max time limit of entering each sequence is 15 seconds.
The code causes the output:
Kindly specify the length of the sequence: 3
Kindly specify the number of the colors in the sequence: 3
Input sequence:
Sorry, I got tired waiting for your input. Good bye!
Input sequence:
instead of
Kindly specify the length of the sequence: 3
Kindly specify the number of the colors in the sequence: 3
Input sequence:
I mean it does not let me enter the sequence on the line 3 of output but rather goes ahead and finishes one loop of timer and then lets me input the sequence. Why is that? This does not happen if i remove the printf
and scanf
functions in the following main()
code.
Here is my code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define INPUT_LEN 10
/* read a guess sequence from stdin and store the values in arr */
void readString(int *arr)
{
fflush(stdout);
time_t end = time(0) + 15; //15 seconds time limit.
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
char answer[INPUT_LEN];
int pos = 0;
while (time(0) < end)
{
int c = getchar();
/* 10 is new line */
if (c != EOF && c != 10 && pos < INPUT_LEN - 1)
{
answer[pos++] = c;
}
/* if new line entered we are ready */
if (c == 10)
break;
}
answer[pos] = '\0';
if (pos > 0)
{
int x = 0;
char *ptr = strtok(answer, " ");
while (ptr != NULL)
{
sscanf(ptr, "%d", (arr + x++));
ptr = strtok(NULL, " ");
}
}
else
{
puts("\nSorry, I got tired waiting for your input. Good bye!");
// exit(EXIT_FAILURE);
}
}
int main()
{
int seqlen = 0, colors = 0;
printf("Kindly specify the length of the sequence: ");
scanf("%d", &seqlen);
printf("Kindly specify the number of the colors in the sequence: ");
scanf("%d", &colors);
int *guessSeq = (int *)malloc(sizeof(int) * 5);
int found = 0, attempts = 0;
while (!found)
{
if (++attempts > 10)
break;
/* IMPLEMENT the main game logic here */
printf("Input sequence: ");
readString(guessSeq);
}
return (0);
}