我想在 Ubuntu 上写一个 C++ 程序,
无需按回车即可立即对输入使用react。
(-> 由于我在 UNIX 系统上工作,我不能使用 header #include <conio.h>
)
例如: 我在键盘上按下键“a”,但没有在终端中显示“a”, 该程序应显示“p”。
在过去的两天里,我尝试用标题 #include <ncurses.h>
来做到这一点.
不幸的是,它不起作用。
因此,我想请求您的请求。
conio.h 会是这样的:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main(void)
{
char c;
c = getch();
while(true)
{
if(c=='a')
{
putch('p');
}
else
{
putch(c);
}
c = getch();
}
cin.sync();
cin.get();
}
你能不能简单地用#include <ncurses.h>
发布工作源代码?而不是 #include <conio.h>
?
提前致谢!!!
致以最诚挚的问候
夸克42
谢谢 Paulo1205!!!!
这是没有 conio.h 的最终代码:
#include <iostream>
#include <string>
#include <unistd.h>
#include <termios.h>
#include <ncurses.h>
using namespace std;
int my_getch(void){
struct termios oldattr, newattr;
unsigned char ch;
int retcode;
tcgetattr(STDIN_FILENO, &oldattr);
newattr=oldattr;
newattr.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
retcode=read(STDIN_FILENO, &ch, 1);
tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
return retcode<=0? EOF: (int)ch;
}
int main(void)
{
char c;
c = my_getch();
while(true)
{
if(c=='a')
{
putchar('p'); fflush(stdout);
}
else
{
putchar(c); fflush(stdout);
}
c = my_getch();
}
cin.sync();
cin.get();
}
最佳答案
如果您只想快速替换旧的 ConIO getch
(),则以下代码就足够了。
int my_getch(void){
struct termios oldattr, newattr;
unsigned char ch;
int retcode;
tcgetattr(STDIN_FILENO, &oldattr);
newattr=oldattr;
newattr.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
retcode=read(STDIN_FILENO, &ch, 1);
tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
return retcode<=0? EOF: (int)ch;
}
但是请注意,旧的 DOS ConIO 是 UNIX Curses 包的精简版,它提供了文本终端屏幕操作所需的一切。
编辑无论如何,诅咒肯定是最佳选择。如果您想要处理箭头键或功能键,而不必为每种类型的终端了解与它们关联的转义序列而烦恼,您宁愿学习 Curses 及其自己的 getch 版本()
。
此外,如果您认为您需要支持 UTF-8 或任何其他多字节表示的 ASCII 范围之外的字符,您最好使用 ncursesw 库的函数 get_wch()
及其姐妹。
关于c++ - 为 conio.h 使用另一个 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34025002/