简体   繁体   English

C ++,While循环中的实时用户输入

[英]C++, Real-Time User Input, during While Loop

Is there was any way for the User to give a Real-Time input, while something is constantly being updated in the background. 用户有什么办法可以提供实时输入,而某些内容会在后台不断更新。 Basically, making the program not stop, when asking for user input. 基本上,在要求用户输入时使程序不停止。

For example, It will ask for user input, while a number is constantly being calculated. 例如,它将在不断计算数字的同时要求用户输入。

There are two ways of this problem, as I see it. 我认为有两种方法可以解决此问题。

One is, as xebo commented, using multi threading. 正如xebo所说,一种是使用多线程。 Use one thread for the constant calculation of the number or whatever, and another thread to look for user input constantly. 使用一个线程不断地计算数字或其他内容,使用另一个线程不断寻找用户输入。

The second method is a simpler on and works only if you are using cin( from the std namespace) to get user input. 第二种方法更简单,仅当您使用cin(来自std名称空间)获取用户输入时才有效。 You can nest another while loop inside the calculation loop like this: 您可以在计算循环中嵌套另一个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;
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM