Thread: Failure to create delay in a loop with printf(). Why?

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    4

    Failure to create delay in a loop with printf(). Why?

    I have been tinkering with a fairly simple program. One of the goals is to fetch a character from a text file and print it to the screen. This done in a loop with a delay so that, let's say, "Hello World.", would print 1 letter per second.

    Where LL is a value I'm tinkering with to control the amount of delay...
    Code:
            for (cntr3=0; buffmain[cntr3]!='\0'; cntr3++)
            {
                printf("%c", buffmain[cntr3]);
                for (time1=0; time1<LL; time1++)
                {
                    ;
                }
            }
    The problem seems to be that instead of printing a character, then completing the |||for||| loop, then starting over, is that the entire contents of |||buffmain||| are printed to the screen, then, it seems the |||for||| loop is run consecutively |||cntr3||| number of times separately.

    I think I have a, "feel", for what is happening here, but if anyone can elaborate on the, "why", It would be greatly appreciated. I originally started out using |||usleep()|||, but tried doing it this way as the same problem arose.

    I'm working with the GNU GCC compiler if that makes a difference. Also, is there any way around this to achieve the desired effect?
    Last edited by TropicalStarfis; 02-15-2012 at 12:53 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    printf() goes to stdout, which is usually buffered.

    So you only see the buffer when
    - it is full
    - you print a newline
    - you explicitly call fflush()

    Try say
    Code:
    printf("%c", buffmain[cntr3]);
    fflush(stdout);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2011
    Posts
    4
    Phenomenal. I Had no idea the solution would be so simple. Many thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. for loop failure...
    By trievideo in forum C Programming
    Replies: 5
    Last Post: 01-23-2011, 09:28 AM
  2. Set delay time between printf() statements
    By SilentPirate007 in forum C Programming
    Replies: 7
    Last Post: 03-23-2010, 05:04 PM
  3. Create a delay function
    By ThLstN in forum C Programming
    Replies: 5
    Last Post: 01-06-2008, 02:54 PM
  4. Create a delay without using Sleep
    By Bag a Bones in forum C++ Programming
    Replies: 12
    Last Post: 01-25-2006, 10:35 PM
  5. How can I create a time delay?
    By Guideon72 in forum C Programming
    Replies: 14
    Last Post: 10-25-2001, 02:28 PM