Time

怎么写一个我爱你程序在某段时间执行?比如说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
Well, this automatic translation doesn't make sense. At least for me.
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
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();    
}

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.
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

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