Home > Net >  Elegant Text Animation in C
Elegant Text Animation in C

Time:02-03

Is there any way to animate a text output in C? I am relatively new to programming and am trying to accomplish something similar to this bit of python code but haven't been able to find anything online. All insights are welcome. Thank you for reading.

#python text animation
import time 
import sys

def delay_print(s):
     for c in s:
          sys.stdout.write(c)
          sys.stdout.flush()
          time.sleep(0.02)

delay_print("hello world")

CodePudding user response:

Here's a cross platform example that should work on almost any OS:

#include <stdio.h>

// check if being compiled for windows or posix (linux/bsd/mac)
#ifdef _WIN32
    // include minimal windows headers
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
#else
    // include posix headers
    #include <time.h>
#endif

void milli_sleep(unsigned int milliseconds);
void delay_print(char* str, unsigned int milliseconds);

int main()
{
    delay_print("Hello World\n", 20); // 20 milliseconds = 0.02 seconds
    return 0;
}

void delay_print(char* str, unsigned int milliseconds)
{
    for (; *str; str  ) {
        putchar(*str);
        fflush(stdout);
        milli_sleep(milliseconds); 
    }
}

void milli_sleep(unsigned int milliseconds)
{
#ifdef _WIN32
    // use windos Sleep function, sleeps for a number of milliseconds
    Sleep(milliseconds);
#else
    // use posix nanosleep function, sleeps for a number of nanoseconds
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000L;
    nanosleep(&ts, NULL);
#endif
}

CodePudding user response:

Here is an example:

#include <stdio.h>
#include <unistd.h>
 
void delay_print(char *str)
{
    for (char *p = str; *p; p  ) {
        putchar(*p);
        fflush(stdout);
        usleep(20000);
    }
    putchar('\n');
}

int main(void)
{
    delay_print("Hello world!")
    return 0;
}
  •  Tags:  
  • Related