Search code examples
coutputflush

Can i fflush multiline output?


Is there any way that I can fflush() a multi-line output? For example, if I wanted to print a 5x5 array in 5 separate lines and shuffling it multiple times every 1 second, how am I supposed to use fflush()?

#include <stdio.h>
#include <stdlib.h>
int main(){
    int arr[5][5]; //Just an array of numbers
    for(int k = 0; k < 10; k++){
        for(int i = 0; i < 5; i++){
            for(int j = 0; j < 5; j++){
                printf("%d ", arr[i][j]);
            }
            printf("\n");
        }
        fflush(stdout);
        shuffle(arr);
        sleep(1);
    }
    return 0;
}

This how i would want the output to change (without of course creating any additional new lines):

 0 1 2 3 4       5 3 12 7 8
 6 7 8 9 10  ->  1 2 0 13 6
     .               .
     .               .
     .               .

I tried both rewind(stdout) and fsetpos() but it didn't seem to do anything.


Solution

  • What you want is called clearing the display. You can do system("cls"); on Windows or system("clear"); on Unixy systems.

    Or there are https://en.wikipedia.org/wiki/ANSI_escape_code - if you print those special characters, stuff will happen, you can move the cursor to the top and overwrite the text or try just clearing the screen. I'm not confident which escape code will work for you, experiment.