Home > Blockchain >  Print number for each second
Print number for each second

Time:10-14

#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??

CodePudding user response:

The problem is probably that the output buffer is not being flushed.

I suggest that you call fflush( stdout ); before the delay(1000); function call.

CodePudding user response:

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);

CodePudding user response:

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

  • Related