gpt4 book ai didi

c++ - 在没有任何干预的情况下继续运行程序,直到它被要求退出

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:26 27 4
gpt4 key购买 nike

下面的代码期望用户在每个循环中键入一个字符。如果我想继续运行此循环而用户不必在每个循环中输入任何字符直到键入数字 0,我该如何实现。

#include<iostream>

int main()
{
int i = 1;
int ch = 1;
while (ch != 0)
{
std::cin >> ch;
std::cout << "Hi" << i << std::endl;
++i;
}
return 1;
}

最佳答案

线程是您唯一的选择。此外,当您使用 std::cin 时,它始终需要 ENTER。这可能有效:

#include <future>
#include <iostream>
#include <thread>

int main(int argc, char** argv) {
int i = 1;
std::atomic_int ch{1};
std::atomic_bool readKeyboard{true};

std::thread t([&ch, &readKeyboard]() {
while (readKeyboard) {
int input;
if (std::cin >> input) {
ch = input;
if (ch == '0') {
break;
}
}
}
});

while (ch != '0') {
std::cout << "Hi" << i << std::endl;
++i;
}

readKeyboard = false;
t.join();
return 1;
}

关于c++ - 在没有任何干预的情况下继续运行程序,直到它被要求退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51759675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com