c++ - 循环获取cin输入

标签 c++ multithreading

是否可以像这样创建一个 while 循环:

bool stop_input = false;

while (!stop_input) {
    // Keep getting inputed string
    // Maybe like std::getline(std::cin, str_input);
}

这将继续循环并在不停止(卡住)的情况下获取用户输入到控制台的内容,就像在执行 std::cinstd::getline() 时一样。

我对此很感兴趣,因为它有一个单独的线程,它会在等待用户输入内容并按回车键时做其他事情,然后 stop_input 会变为 true 并且用户输入会被禁用。

这可能吗?怎么办?

编辑:

例如如果我这样做了:

void test()
{
    std::string str;
    while (!stop_input) {
        std::getline(std::cin, str);
    }
}

如果我像上面那样创建一个函数,编译它并启动调试器,调试器(程序)将在第二次调用 std::getline() 时停止。我不希望这种情况发生,我希望这个循环持续运行直到通过设置 stop_input = true;

停止

编辑2:

主线程:

void someFunction()
{
    string read_input;
    thread get_input = thread(readInput, &read_input);

    while(1) {
        if (buttonPressed(ENTER) {
            stop_input = true;
            get_input.join();

            // Do something with 'read_input' string.
        } else if (buttonPressed(ESC) {
           stop_input = true;
           get_input.join()

           // Discard 'read_input' string and return from this function.
           break;
        }
    }
}

阅读线程:

void readInput(string* input)
{
    while (!stop_input) {
        //Get input
    }
}

附言当然主线程也会在后面做一些与输入读取无关的工作。

最佳答案

我不确定我是否答对了你的问题,但如果你只是想在线程中运行一些东西并允许输入直到线程中的任务完成,我会这样做:

std::vector< int > v;
std::atomic< bool > stop_input( false );
std::thread t( [ &v, &stop_input ]() 
{
  for( int i = 0; 1'000'000'000 > i; ++i ) v.push_back( i );
  stop_input = true;
} );
std::string m;
while( !stop_input )
{
  std::cin >> m;
  std::cout << "Your message: " << m << std::endl;
}
t.join();

但是,这只会在线程中的任务终止后用户输入后终止。它不会“中断”std::cin

关于c++ - 循环获取cin输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210811/

相关文章:

c++ - 更改名称文件放置我的文件 C++ & Qt 的第一行

c++ - 哪些函数可以应用于右值?

c++ - boost 序列化 : pointer conainer to <BASE> contains various of DERIVED objects

c++ - 当 pthread 启动时,它是否需要互斥锁来访问先前在生成它的线程中写入的全局数据

c++ - boost 等效于 ManualResetEvent?

c++ - 消除未使用的虚函数

c++ - 永远不会在 gmock 中调用 C 字符串

multithreading - 如何使用 TableServiceContext.BeginSaveChanges 创建 Silverlight 单元测试?

c# - 为什么这里要用锁?

multithreading - 在 go 例程中更新后未返回更新值