-2

first i used this code:

void pause(long n)
{
  clock_t at=clock();
  while(clock()-at<=n)
    ;    
}

int main()
{
  cout<<1;
  pause(100000);
  cout<<2;
}

what do u expect? output will be 1(some time gap)2 right? NO..!! its (some time gap)12 how?? Anyways, i changed the pause function as follows-

void pause(long n)
{
  for(long i=1; i<=n*n; i++)
    ;
}

Still same thing..!! why this blank for loop executing first?? but if i do this

  void pause(long n)
  {
   for(long i=1; i<=n*n; i++)
     cout<<0  ;
  }

Now it happily executes output as 10000000000....(many 0s)....00002

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 2
    `cout << 1;` doesn't flush the output buffer. Try adding `cout << std::flush;`. Or `cout.flush()` – Captain Giraffe Nov 06 '16 at 16:23
  • 1
    [Cout won't print text without endl inside while loop?](http://stackoverflow.com/q/29315659/995714), [std::cout won't print](http://stackoverflow.com/q/14858262/995714) – phuclv Nov 06 '16 at 16:42

1 Answers1

0

You have forgotten that cout is buffered stream too. If you want to see 1 and 2 immediately you need to call flush

cout.flush()

or

cout << flush;

Note that std::endl also calls flush implicitly

Oleg Bogdanov
  • 1,712
  • 13
  • 19