Home > database >  How to print to terminal one char and then pause and print another?
How to print to terminal one char and then pause and print another?

Time:11-27

I've been trying to print to the terminal with a pause, it's better explained with the following code:

I'm trying to have X print to the terminal and then wait 5s and have X print again but when I run the code, it waits 5s and prints XX can anyone help me get the proper functionality?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static void sleepMs(long long delayMs){
    const long long NS_PER_MS = 1000 * 1000;
    const long long NS_PER_SECOND = 1000000000;
    long long delayNs = delayMs * NS_PER_MS;
    int seconds = delayNs / NS_PER_SECOND;
    int nanoSeconds = delayNs % NS_PER_SECOND;
    struct timespec reqDelay = {seconds, nanoSeconds};
    nanosleep(&reqDelay, (struct timespec *) NULL);
}

int main()
{
    printf("X");
    sleepMs(5000);
    printf("X");
    

    return 0;
}

Thank you in advance, sorry for any missing tags.

EDIT: I want them to print on the same line

CodePudding user response:

You need to flush the output stream if you want to see the result before printing a \n:

putchar('X');
fflush(stdout);
  • Related