【问题标题】:C++, Real-Time User Input, during While LoopC++,实时用户输入,在 While 循环期间
【发布时间】:2013-10-05 03:51:42
【问题描述】:

用户是否有任何方法可以提供实时输入,同时在后台不断更新某些内容。基本上,当要求用户输入时,使程序不会停止。

例如, 它会要求用户输入,同时不断计算一个数字。

【问题讨论】:

  • 多线程就是答案。启动 2 个线程,一个用于计算,一个用于用户输入。

标签: c++ loops input while-loop


【解决方案1】:

在我看来,这个问题有两种方法。

正如 xebo 评论的那样,一个是使用多线程。使用一个线程不断计算数字或其他内容,并使用另一个线程不断查找用户输入。

第二种方法更简单,仅当您使用 cin( 来自 std 命名空间) 时才有效 获取用户输入。您可以像这样在计算循环中嵌套另一个 while 循环:

#include <iostream>
using namespace std;

int main()
{
    int YourNumber;
    char input;         //the object you wish to store the input value in.
    while(condition)    //Whatever your condition is
    {
        while(cin>>input)
        //This while says that the statement after (cin»input)
        //is to be repealed as long as the input operation 
        //cin>>input succeeds, and
        //cin»input will succeed as long as there are characters to read 
        //on the standard input.
        {
             //Update process your input here.
        }
        //D what the normal calculations you would perform with your number.
    }
return 0;
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2020-02-15
    • 2019-08-03
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多