Time

Sep 7, 2017 at 12:54pm
怎么写一个我爱你程序在某段时间执行?比如说5秒后执行。How do I write a program that I love you in a certain time? For example, after 5 seconds to implement.
Last edited on Sep 7, 2017 at 12:57pm
Sep 7, 2017 at 1:09pm
Well, this automatic translation doesn't make sense. At least for me.
Sep 7, 2017 at 1:10pm
Are you on Windows? You can use sleep function to delay text from appearing. Must use Windows API for it to work.

1
2
3
4
5
6
7
8
#include <windows.h>

int main()
{
    // Sleep(number of milliseconds);
    Sleep(5000); // 5 seconds
    std::cout << "I love you" << std::endl;
}


If you compile with C++11, you can do this cross-platform.
This is a better option*:

1
2
3
4
5
6
7
8
9
#include <thread>
#include <chrono>
#include <iostream>

int main()
{
    std::this_thread::sleep_for(std::chrono::seconds(5));
    std::cout << "I love you" << std::endl;
}


*(Chervil's answer is also perfectly good, it let's you control 2x threads asynchronously)
Last edited on Sep 7, 2017 at 1:25pm
Sep 7, 2017 at 1:18pm
Another variation using threads:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <thread>
#include <chrono>


void message()
{
    std::this_thread::sleep_for(std::chrono::seconds(5));
    
    std::cout << "\nI love you\n";    
}

int main()
{
    std::thread  one(message);
    

    for (int i=0; i<20; i++)
    {
        std::cout << i << '\n';
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    
    
    one.join();    
}

Sep 7, 2017 at 1:27pm
s.b I mean using c ++ standard library to write. Do not mention me with windows, that is an alternative. If you look at the windows kernel source code, you will feel how bad windows! Bug too much. I suggest you still use linux or like unix. After all, Unix and linux stability. If you do not think of my idea, that does not matter.
Sep 7, 2017 at 1:28pm
I agree, windows can be bad. I do use Linux for many things.

std::thread and Chervil's answer only use C++ standard library, and are multi-platform.
Last edited on Sep 7, 2017 at 1:38pm
Sep 7, 2017 at 1:38pm

do you use github?
Sep 7, 2017 at 1:39pm
I think about you learning and working with you to write code
Sep 7, 2017 at 6:13pm
:) No thank you, but feel free to ask more questions on the forum!
Topic archived. No new replies allowed.