我最近尝试过cpp,在我正在制作的东西中,我正试图让它变成值为20的变量每秒减去1,但我还需要机器等待来自用户的输入。我尝试使用for循环,但在放置输入或变量用完之前它们不会继续。我看着时钟,但它们似乎不符合我的需要,或者我只是误解了它们的目的。
有什么建议吗?
答案 0 :(得分:0)
正如评论中已经提到的那样,线程化是实现此目的的一种方法。有一个很好的自包含示例here(我在下面的代码中借用了它)。
在下面的代码中,启动了异步功能。有关这些here的详细信息。这将返回一个future
对象,该对象将在作业完成后包含结果。
在这种情况下,作业正在侦听cin
(通常是终端输入),并在输入某些数据时返回(即按下输入时)。
与此同时,while循环将运行,它会跟踪已经过了多少时间,减少计数器,并在异步作业完成时返回。如果这正是您想要的行为,那么您的问题并不清楚,但它会给您提供想法。它将打印出递减变量的值,但是用户可以输入文本,一旦用户按下输入,它就会打印出来。
#include <iostream>
#include <thread>
#include <future>
#include <time.h>
int main() {
// Enable standard literals as 2s and ""s.
using namespace std::literals;
// Execute lambda asyncronously (waiting for user input)
auto f = std::async(std::launch::async, [] {
auto s = ""s;
if (std::cin >> s) return s;
});
// Continue execution in main thread, run countdown and timer:
int countdown = 20;
int countdownPrev = 0;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point end;
double elapsed;
while((f.wait_for(5ms) != std::future_status::ready) && countdown >= 0) {
end = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();
countdown = 20 - (int) (elapsed/1000);
if (countdown != countdownPrev) {
std::cout << "Counter now: " << std::fixed << countdown << std::endl;
countdownPrev = countdown;
}
}
if (countdown == -1) {
std::cout << "Countdown elapsed" << std::endl;
return -1;
} else {
std::cout << "Input was: " << f.get() << std::endl;
return 0;
}
}
P.S。要使我的编译器工作,我必须使用g++ -pthread -std=c++14 file_name.cpp
编译它以正确链接线程库并允许使用c ++ 14功能。