printf just before a delay doesn't work in C

前端 未结 5 560
别那么骄傲
别那么骄傲 2020-12-11 05:23

Does anyone know why if i put a printf just before a delay it waits until the delay is finished before it prints de message?

Code1 with sleep():

int          


        
相关标签:
5条回答
  • 2020-12-11 05:58

    printf buffers it's output until a newline is output.

    Add a fflush(stdout); to flush the buffers on demand.

    0 讨论(0)
  • 2020-12-11 05:58

    When you call printf, you don't print anything until really necessary: until either the buffer fulls up, or you add a new line. Or you explicitly flush it.

    So, you can either do

    printf("Something\n");
    delay();
    

    or

    printf("Something");
    fflush(stdout);
    delay();
    
    0 讨论(0)
  • 2020-12-11 06:07

    Normally, standard output is buffered until you either:

    • output a \n character
    • call fflush(stdout)

    Do one of these things before calling delay() and you should see your output.

    0 讨论(0)
  • 2020-12-11 06:09

    Technically that shouldn't even compile. In the delay("sleep 3") call you're trying to convert a const char * to a float. It should be:

    void delay (float sec)
    {
        // ...
    }
    
    delay(3);
    
    0 讨论(0)
  • 2020-12-11 06:15

    the standard output is not flush until you output a '\n' char.

    try printf ("hi world\n");

    0 讨论(0)
提交回复
热议问题