While循环期间的C++实时用户输入
问题描述:
用户是否有任何方式给予实时输入,而某些内容在后台不断更新。基本上,当要求用户输入时,使程序不停止。While循环期间的C++实时用户输入
例如, 它会要求用户输入,而一个数字是不断计算的。
答
这个问题有两种方法,就像我看到的那样。
正如xebo评论的那样,使用多线程。使用一个线程来持续计算数字或其他内容,另一个线程可以不断地查找用户输入。
第二种方法比较简单,只有在您使用cin(来自标准名称空间) 才能获得用户输入时才有效。您可以在计算循环内嵌入另一个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;
}
希望这会有所帮助。
多线程就是答案。开始2个线程,一个用于计算,另一个用于用户输入。 – ervinbosenbacher