您能否在不使用 GetAsyncKeyState 或线程的情况下为 Windows 程序运行 C++ 中的函数的同时获取用户输入? [英] Can you simultaneously get user input while also running a function in C++ for a windows program without using GetAsyncKeyState or threading?
问题描述
我有一个项目,我正在使用 Dev-C++ 作为 IDE,使用 Windows 作为操作系统.由于项目因大小限制和当前知识而在复杂性上受到限制,我宁愿避免使用 GetAsyncKeyState
和线程,除非我可以使用一种相当简单(少于 10 行)的方法.>
我的程序当前使用 Text
函数使用字符串显示文本并将它们输出到控制台窗口.我想实现一个功能,允许用户按下一个键,并允许在不等待函数读取整个字符串的情况下打印出文本.
例如:
<块引用>欢迎来到……"[用户在文本缓慢时按空格键逐个字符显示]
"欢迎收看我的节目!这是我开发的!"[整个字符串是显示]
代码:
void Text(字符串输入){整数 x = 0;for(int i = 0; i <= 3; i++)//根据字符串数量决定何时停止运行{while (input[x] != '\0'){if(input[x] == '.' || input[x] == '!'){cout<<输入[x];睡眠(375);cout<<"";x++;}否则如果(输入 [x] == '*'){睡眠(375);cout<<结束;x++;}否则如果(输入 [x] == '~'){睡眠(2000);系统(CLS");x++;}别的{cout<<输入[x];睡眠(75);x++;}}}}
不,您不能采用可移植的方式.原因是通常控制台上的标准 I/O 会等待一行完成,因此您无法在键入后立即捕获单个字符.
不过,您可以使用非标准函数来实现这一点!请参阅 无需等待即可从标准输入中捕获字符按下回车
I have a project that I am working on using Dev-C++ as the IDE and Windows as the operating system. As the project is restricted in complexity due to size constraints and current knowledge, I would prefer to avoid using GetAsyncKeyState
and threading unless there is a fairly simple (less than 10 lines) approach I could use.
My program currently displays text using the Text
function using strings and outputting them to the console window. I want to implement a feature that would allow the user to press a key, and allow the text to print out without waiting for the function to read the entire string.
For example:
"Welcome to ..." [user presses space bar while the text is slowly being displayed character by character]
"Welcome to my program! This was developed by me!" [entire string is displayed]
Code:
void Text(string input)
{
int x = 0;
for(int i = 0; i <= 3; i++) //decides when to stop running based on number of strings
{
while (input[x] != '\0')
{
if(input[x] == '.' || input[x] == '!')
{
cout << input[x];
Sleep(375);
cout << " ";
x++;
}
else if(input[x] == '*')
{
Sleep(375);
cout << endl;
x++;
}
else if(input[x] == '~')
{
Sleep(2000);
system("CLS");
x++;
}
else
{
cout << input[x];
Sleep(75);
x++;
}
}
}
}
No, you cannot in a portable way. The reason is that standard I/O on the usual consoles wait for a line to be completed, so you cannot capture single characters as soon as they are typed.
You can achieve that with non-standard functions, though! See Capture characters from standard input without waiting for enter to be pressed
这篇关于您能否在不使用 GetAsyncKeyState 或线程的情况下为 Windows 程序运行 C++ 中的函数的同时获取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!