获取或不获取用户输入
Getting OR not user input
我的代码有问题。事实上,它很好用,我只是在寻找更好的解决方案。我所做的是这样的(它只是整体的一部分,不需要张贴其他部分,因为它只需要在这里):
#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;
}
相关文章:
- 如何从用户那里获取输入并将其存储在向量中?
- 代码在执行之前终止,并且没有从用户那里获取输入
- 从用户获取输入/输出
- TFLite 隔离错误,通过获取C++输入和输出
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- 使用 qt 或 c++ 从桌面获取输入和输出
- 您如何在C++中不断获取输入?
- 从源代码本身C++获取输入
- 函数,从问题中获取输入,并在主函数中使用该输入
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 如何在 std::map 中从 std::vector of std::p air 中获取输入?
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- 从用户获取输入
- 我需要编写一个代码,从用户那里获取输入(句子)并停止在@处
- C 程序在获取输入[控制台应用程序]时跳过行
- 我在C++从函数中的用户获取输入、添加到数组和打印该数组时遇到问题
- 从用户那里获取输入,直到他输入一个数字
- 如何使用数组获取输入,并将其存储在record.h类的主类中的变量中
- getline 语句未获取输入
- 用户定义的功能用于竞争编程中,以获取输入