ctimeprintfsleepseconds

Print out seconds on screen by replacing them without clear screen


I've tried but still dont know yet. I want to print out the result like this: seconds(10) -> seconds(9) -> ... -> seconds(1) by replacing each integer in every second without system("cls").

sample program


Solution

  • You could print \r to return the cursor to the beginning of the line.

    Example:

    #include <stdio.h>
    #include <threads.h>
    
    int main() {
        struct timespec st = {.tv_sec = 1, .tv_nsec = 0};
    
        for(int i = 10; i>=0; --i) {
            printf("%2d\r", i);    // \r to return to the beginning of the line
            fflush(stdout);        // flush to ensure it's actually printed
    
            thrd_sleep(&st, NULL); // sleep a second
        }
    }