Search code examples
csleepoutput-buffering

Having problems with the sleep function inside a loop in C


I'm writing a code in C and the sleep function is not working as I want.

for(seq_n = 1; seq_n <= 3; seq_n++){
    printf("Sequence %d:\n", seq_n);
    for(val_n = 1; val_n <= 5; val_n++){
        seq[val_n] = rand() % 9;
        printf(" %d", seq[val_n]);
    }

    sleep(5);

    printf("\nType the Sequence: \n");
    for(val_n = 1; val_n <= 5; val_n++)
        scanf("%d", &seq_user[val_n]);
        checkSequence(seq, seq_user);
}

When I run the program, it first appears "Sequence (number)" and then only after 5 seconds the sequence and the phrase "Type the Sequence" is printed, at the same time , occuring this in the whole loop.

I want that "Sequence (number)" appears at the same time as the sequence, and only after 5 seconds the program asks to type the sequence. Besides, I would like to know how to make the sequence disappear after the 5 seconds.

How can I do this?


Solution

  • Change to:

    printf("\n");
    sleep(5);
    printf("Type the Sequence: \n");
    

    The output is buffered until a newline.