0

So basically I just want to read characters from the user and make my code know that when user types a defined combination (say, CTRL+F - but without confirming with Enter, for exmaple), it's the end of the input. How can I do that? I only know how to read characters with enter and comparing their ASCII's...

4

3 回答 3

1

编辑再次阅读您的问题,我意识到我误解了您的问题。我会留下这个,因为它可能对你或其他人仍然有用。


您所要求的与阅读字符无关。事实上,CTRL 根本不是一个字符。你基本上只是在检查按键。处理这种输入依赖于平台,即使在一个平台上,也会存在多种方法。对 Windows 执行此操作的一种方法是使用GetAsyncKeyState. 此功能将检查是否正在按下指定的键。请注意,它不会“记住”输入,因此您必须每秒多次检查此功能才能注册所有用户输入。

您为函数提供一个参数,指定要检查其状态的键。可以在此处找到所有关键代码的列表

例子:

#include <iostream> //for output
#include <windows.h> //for GetAsyncKeyState

int main()
{
    while(true)
    {
        if( GetAsyncKeyState(VK_CONTROL) ) //CTRL-key is pressed
        {
            if( GetAsyncKeyState( 0x46 ) ) //F-key is pressed
                std::cout << "CTRL-F is pressed" << std::endl;
            if( GetAsyncKeyState( 0x58 ) ) //X-key is pressed
                break;
        }
    }
    std::cout << "CTRL-X was pressed, stopping.." << std::endl;
}

这个例子将不断地检查是否CTRL-F正在被推送,如果是,则写入输出,直到CTRL-X被按下。

于 2013-03-21T15:48:33.413 回答
0

尝试

#include <conio.h>
#include <iostream>
using namespace std;

int main()
{
     bool keepGoing = true;
     char key = ' ';
     while (keepGoing){
       cout << "Enter a key" << endl;
       while(_kbhit()){
         key = _getch();
         cout << "You entered: " << key << endl;
       }
     }
}

然后指定何时结束循环的分隔符。

如果在 linux curses 上可用。还有一个 getch 功能。如果你的目标是跨平台兼容性,你应该使用 curses。ncurses 库函数类似于 conio.h 中的函数。 ncurses 教程

于 2013-03-21T15:42:02.327 回答
0

Windows 系统调用ReadConsoleInput允许您直接读取控制台输入。您可能希望将该调用包装到一个函数中,该函数仅从函数的几个参数中提取基本数据ReadConsoleInput。您可以编写一个函数来检查是否有任何输入GetNumberOfConsoleInputEvents

于 2013-03-21T15:47:57.827 回答