C++, Real-Time User Input, during While Loop

2019-04-18 00:15发布

问题:

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.

回答1:

There are two ways of this problem, as I see it.

One is, as xebo commented, using multi threading. 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. You can nest another while loop inside the calculation loop like this:

#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.