0

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?

melpomene
  • 79,257
  • 6
  • 70
  • 127
sabonet
  • 3
  • 2
  • 1
    You should have a `fflush(stdout);` before the sleep. – Shawn Apr 02 '19 at 21:48
  • ...because stdout is line-buffered and data is only written after each line. https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – cfillion Apr 02 '19 at 21:53

2 Answers2

1

Change to:

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

The output is buffered until a newline.

MFisherKDX
  • 2,741
  • 3
  • 11
  • 25
1

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.

melpomene
  • 79,257
  • 6
  • 70
  • 127