获取或不获取用户输入

Getting OR not user input

本文关键字:获取 输入 用户      更新时间:2023-10-16

我的代码有问题。事实上,它很好用,我只是在寻找更好的解决方案。我所做的是这样的(它只是整体的一部分,不需要张贴其他部分,因为它只需要在这里):

#include <windows.h>
int main(){
    int a = 0, int b = 3;
    while(true) {
        a = a * a + b;
        Wait(1000);
    }
    return 0;
}

我想实现的是随时改变变量b的能力。到目前为止,我发现最好的解决方案是使用getche(),因为它不需要每次都按enter,但我仍然必须每次都放一些东西。完美的解决方案是这样的:如果用户想要更改b,他就输入一个新值(只需要一个数字),否则循环就会一直继续下去。什么好主意吗?我将感激任何帮助!

c++标准库没有定义非阻塞读函数。你可以创建一个读取线程,它阻塞读取,并设置一个适当的同步变量,从另一个正在进行计算的线程中读取。但我不会追求这个方向。

相反,我会使用一些平台特定的设置将std::cin设置为非阻塞。在UNIX上,您将使用fcntl()将标准输入流置于非阻塞输入模式:

int flags = fcntl(0, F_GETFL);
fcntl(0, F_SETFL, flags | O_NONBLOCK);
unsigned long count(0);
for (char value(0); !(std::cin >> value) || value != '1'; ) {
    std::cin.clear();
    ++count;
}
std::cout << count << 'n';

也许是这样的?我还没有测试过。

#include <thread>
#include <iostream>
using namespace std;
bool loop;
int a = 0, b = 0;
void multiplication () {
    while(loop) {
        a += b;
        b = 0;
        // wait(1000);
        cout << "a = " << a << endl;
    }
}
int main () {
   loop = true;
   thread myThread(multiplication);
   while(b != -1) {
       cin >> b;
   }
   loop = false;
   cout << "done!" << endl;
}