2

Explanation

Take for example this basic code.

#include <iostream>
#include <thread>

int main(int argc, const char * argv[]) {
    while(true){
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::cout << "loop";
    }
}

When I run this in XCode, it works exactly as expected. Every second it prints out, "loop". However, when I run this in my terminal, nothing happens. The code seems to be "running" but nothing gets printed to screen.

Question:

Why does std::this_thread::sleep_for() work in the XCode terminal but not the standard MacOS terminal?

kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
  • 3
    Because the "terminal" buffers your `stdout` whereas it gets flushed immediately by Xcode. Either flush stdout yourself or add `std::endl` at the end which does it implicitly – JustSid Mar 28 '18 at 16:44
  • 1
    @JustSid: Answers in the answers section please. – Bathsheba Mar 28 '18 at 16:47
  • @Bathsheba I was writing a fully fleshed out answer after posting the comment. I have incorporated parts of it into the community wiki answer – JustSid Mar 28 '18 at 16:48
  • Possible duplicate of [cout not working in the case of an infinite loop](https://stackoverflow.com/questions/32652591/cout-not-working-in-the-case-of-an-infinite-loop) – jww Mar 28 '18 at 18:02

1 Answers1

4

std::this_thread::sleep_for() works just fine in the Terminal as well, the problem is that stdout is buffered on the terminal. stdout can either be explicitly flushed or it can be flushed implictly either if it the buffer gets too full or when encountering something like a new line character.

Either flush stdout yourself or add std::endl at the end which does it implicitly.

You could also use std::cerr << "loop"; as the error stream is often unbuffered (although the C++ standard does not insist on that).

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Bathsheba
  • 231,907
  • 34
  • 361
  • 483