You are not logged in.

#1 2016-07-31 17:58:58

mazhar
Member
From: Sanandaj
Registered: 2016-07-12
Posts: 60

[solved] usleep issue in loop C++

Hi there, im observing issue with usleep. For example in this code:

#include <stdio.h>
#include <iostream>
#include <unistd.h>
using namespace std;

int main() {
for(int i=0;i<100;i++) {
                cout<<i+1;
                unsigned int sleep_time = 100000; 
                usleep(sleep_time);
}
return 0;
}

The problem:
program wont write output then sleep then next output, instead it waits a long time then shows all outputs in once.
What should i do? hmm

Last edited by mazhar (2016-08-01 16:47:30)


We are archers, we live in dark to serve the light.

Offline

#2 2016-07-31 19:00:19

stronnag
Member
Registered: 2011-01-25
Posts: 61

Re: [solved] usleep issue in loop C++

no, you're observing buffered output

Offline

#3 2016-07-31 23:21:23

The Infinity
Member
Registered: 2014-07-05
Posts: 91
Website

Re: [solved] usleep issue in loop C++

Just add << std::flush to cout line.

Offline

#4 2016-08-01 05:06:14

mazhar
Member
From: Sanandaj
Registered: 2016-07-12
Posts: 60

Re: [solved] usleep issue in loop C++

The Infinity wrote:

Just add << std::flush to cout line.

Thanks, it totally works. is this an obvious concept? what should i read about it?


We are archers, we live in dark to serve the light.

Offline

#5 2016-08-01 10:13:57

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,530
Website

Re: [solved] usleep issue in loop C++

stronnag wrote:

you're observing buffered output

It would also "work" if you added a newline after each number.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

Board footer

Powered by FluxBB