Search code examples
cloopsprintfgeany

Slowly Appears printf, in C99


I want to make a func similar to a printf but that make the text appears slowly, by using a double for, one to print a char and one to take time:

    char phrase[30]={"Printf random"};
    for(int a=0;a<=30;a++){
        printf("%c",phrase[a]);
        for(int t=0;t<=1000000;t++){
            int f;
            f++;
        }
    }

but when I run, at first, it take some seconds (for the second for), and then it print all the phrase.

Why doesn't it enter the second for every time the firs one does? Maybe once the program calculates the second for the first time, it don't take time to calculate it again? how can i fix it?


Solution

  • First of all, in your code, by saying

     for(int a=0;a<=30;a++){    
    

    you're off-by-one and it invokes undefined behavior. It should be

     for(int a=0;a<30;a++){
    

    That said, you need to flush the output buffer to actually send the buffer content to the associated file. Otherwise, the standard output actually being line-buffered, it will not flush the content automatically. All the content will be stored in the buffer and when the program is about to get finished, all the open buffers will be flushed and then the whole content will appear altogether.