sabonet
sabonet

Reputation: 13

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?

Upvotes: 1

Views: 848

Answers (2)

melpomene
melpomene

Reputation: 85767

If you're printing to a terminal, stdout is line buffered, i.e. output accumulates in an internal buffer until you print \n. (If output is not going to a terminal, stdout is block buffered, so it will only output anything when the buffer runs full.)

To flush the buffer (i.e. to output its contents immediately), you need

fflush(stdout);

before your sleep call.

To clear the current line, you can try

printf("\033[2K");  // erase the line the cursor is in

I'm assuming you're using a common unix terminal emulator; these escape sequences are system specific.

Upvotes: 1

MFisherKDX
MFisherKDX

Reputation: 2866

Change to:

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

The output is buffered until a newline.

Upvotes: 1

Related Questions