1
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>


int main(void)
{
    wiringPiSetupGpio();
    
    for(int i = 0 ; i <50; i++)
    {   
        if ( i%10 == 1)
        {
            printf("\n");
        }
    
        printf("%d  ", i);
        
        delay(1000);
        
    }
    
    
    return 0;
} 

I'm working in rasberry pi environment. I want to print a number for each 1 second. But this code did not print a number one by one but print 10 numbers for each 10 seconds. This code gives 10 numbers in line at once. What's the problem??

wdy0308
  • 19
  • 1

3 Answers3

3

The stdout channel is line buffered by default. This means that data sent to stdout won't necessarily appear until a newline character is printed.

If you call fflush(stdout), any buffered output will be immediately printed.

printf("%d  ", i);
fflush(stdout);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • @wdy0308 Glad I could help. Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush Oct 13 '21 at 16:06
1

The problem is probably that the output stream is not being flushed. I suggest that you call fflush( stdout ); before the delay(1000); function call. This will ensure that all printed data actually becomes observable, before the program enters a wait state.

Normally, it is not necessary to explicitly flush an output stream, because the output will become visible sooner or later. For example, the output buffer will usually get implicitly flushed whenever you read input or when the program ends. Also, if your program is writing output to the user's screen (in contrast to, for example, writing output to a file), then the output stream is probably line-buffered, which means that the output stream will get implicitly flushed whenever a newline character is written.

However, in this case, it appears that the implicit flushing mentioned above is not sufficient. Therefore, you will have to revert to explicit flushing using the function fflush, as mentioned above.

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
1

in order to print the values at the running time using printf you need to add \n so try this may work.

#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h>


int main(void)
{
    wiringPiSetupGpio();
    
    for(int i = 0 ; i <50; i++)
    {   
        if ( i%10 == 1)
        {
            printf("\n");
        }

// a `\n` added at the end of the string!
        printf("%d  \n", i);
        
        delay(1000);
        
    }
    
    
    return 0;
} 

for more info read this question's answer

DarkSide77
  • 719
  • 1
  • 4
  • 21
  • 1
    Assuming that the output stream is line-buffered, then adding a `\n` character has the same effect as calling `fflush( stdout );`, except that it will also output a newline character, which may not be desired. – Andreas Wenzel Oct 13 '21 at 16:47