Why is this program waiting 10 seconds instead of counting?

I tested some C ++ 11 code, and I tried to write a program that counts from 10, sleep between pins. Here is what I still have:

#include <iostream>
using namespace std;

#include <chrono>
#include <thread>

void Sleep(int x)
{
        std::this_thread::sleep_for(std::chrono::duration<int>(x));
}

int main()
{
    for (int x=10; x>0; x--) {
            cout << x << "...";
            Sleep(1);
    }

    cout << " FIRE!!\n";
}

The problem is that this code waits 10 seconds and then prints all the output, rather than counting from 10. How does this happen? And how can I fix this?

(By the way, I tried this on a computer running Linux Mint 17 and MacOSX 10.9, and both times I got the same result)

+4
source share
2 answers

Perhaps because you are not clearing the exit. try it

cout << x << "..." << flush;

, , . , , , .

+10

, () , .

, std::chrono::duration<> , . , std::chrono::seconds :

#include <iostream>
using namespace std;

#include <chrono>
#include <thread>

void Sleep(int x)
{
    // better to use explicit types for duration
    // for readability
    std::this_thread::sleep_for(std::chrono::seconds(x));
}

int main()
{
    for(int x = 10; x > 0; x--) {
        cout << x << "..." << std::flush; // need to flush here
        Sleep(1);
    }

    cout << " FIRE!!\n";
}
+1

Source: https://habr.com/ru/post/1605836/


All Articles