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

标签 c++ loops c++11

下面的代码期望用户在每个循环中键入一个字符。如果我想继续运行这个循环而用户不必在每个循环中输入任何字符直到键入数字 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/

相关文章:

python - 当句子的所有关键字都包含在字典中时,如何将句子与字典关联?

c++ - MinGW GCC 4.9.1 和浮点确定性

c++ - 如何在 TStringGrid 单元格中绘制按钮

c++ - 如何让派生类调用其他派生类的方法?面向对象设计

c# - C++ 中的 vector 类是否可以像 C# 中的字典类一样使用?

C- 检查字符串中的字符是否属于数组

loops - 如何在 Pandas 中将 DataFrame 的行迭代为系列?

c++ - 疯狂的 unique_ptr 语法

c++ - 命名空间内的宏在 'do' 错误之前给出预期的 unqualified-id

c++ - 无法尝试删除不在 C++ 链接列表中的项目