OS X - 在 if 语句中按键
OS X - Keypress in an if statement
我对C++编程和使用Mac作为计算机很陌生。我已经在互联网上搜索了一段时间,但我仍然找不到解决我问题的好方法。
我正在使用键盘箭头制作一个项目,但我不知道如何在 if 语句中制作按键功能。
所以我正在寻找的解决方案是:
if (up arrow is pressed) {
std::cout << it worked! << std::endl;
}
信息:LLVM编译器,Xcodes命令行工具,Unix,OS X-Sierra。谢谢你的帮助。
好吧,我无法让另一个答案中的代码工作,不确定有什么不同,因为我也在运行 Sierra。但我将其转换为使用tcsetattr。该调用的目的是将终端置于原始模式,以便它直接发送按键。如果您不这样做,则在您按回车键之前,它不会发送任何内容。
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
static struct termios savemodes;
static int havemodes = 0;
int tty_break(void)
{
struct termios modmodes;
if (tcgetattr(STDIN_FILENO, &savemodes) < 0)
return -1;
havemodes = 1;
modmodes = savemodes;
cfmakeraw(&modmodes);
return tcsetattr(STDIN_FILENO, TCSANOW, &modmodes);
}
int tty_getchar(void)
{
return getchar();
}
int tty_fix(void)
{
if(!havemodes)
return 0;
return tcsetattr(STDIN_FILENO, TCSANOW, &savemodes);
}
int
main(int argc, char *argv[])
{
int i;
if(tty_break() != 0)
return 1;
for(i = 0; i < 10; i++)
printf(" = %dn", tty_getchar());
tty_fix();
return 0;
}
我已经将我在注释中链接到的代码放在一个程序中,以便您可以看到它是如何工作的。
#include <stdio.h>
#include <sgtty.h>
static struct sgttyb savemodes;
static int havemodes = 0;
int tty_break()
{
struct sgttyb modmodes;
if(ioctl(fileno(stdin), TIOCGETP, &savemodes) < 0)
return -1;
havemodes = 1;
modmodes = savemodes;
modmodes.sg_flags |= CBREAK;
return ioctl(fileno(stdin), TIOCSETN, &modmodes);
}
int tty_getchar()
{
return getchar();
}
int tty_fix()
{
if(!havemodes)
return 0;
return ioctl(fileno(stdin), TIOCSETN, &savemodes);
}
main()
{
int i;
if(tty_break() != 0)
return 1;
for(i = 0; i < 10; i++)
printf(" = %dn", tty_getchar());
tty_fix();
return 0;
}
您可以简单地编译它:
clang main.c -o main
并运行它:
./main
您将看到 ↑(向上箭头(键导致以下代码:
27 (Escape)
91
65
请注意,代码不是我的 - 它完全是从我上面提到的 C-FAQ 中提取的。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 我似乎对if/else的基本语句有问题:/
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果中的多个语句是否与多个 if 相同?
- C++ If/Else 语句被跳过
- 使用语句if时逻辑的问题
- 如何添加语句if-else
- 如何将语句if(isalpha(c))从c++转换为MIPS ?
- 在if语句if C++中创建对象时出现作用域问题
- if语句-if/else和参数放置C++