打印的内容似乎不太对
代码:
#include<stdio.h> #include<termios.h> #include<unistd.h> int main(int argc, char *argv[]) { struct termios new_tm, old_tm; // get the current terminal settings to old_tm. tcgetattr(fileno(stdin), &old_tm); // Copy the old terminal settings to new_tm. new_tm = old_tm; // Cancel echo // new_tm.c_lflag &= ~(ICANON | ECHO); // 关闭规范模式和回显; // This only cancels the echo // new_tm.c_cc[VTIME] = 0; // 超时时间为0秒 // new_tm.c_cc[VMIN] = 1; // 最少需要1个字符 //set new terminal attributes to raw . cfmakeraw(&new_tm); // sets the terminal to something like the "raw" mode of the old Version 7 terminal driver: input is available character by character, echoing is disabled, and all special processing of terminal input and output characters is disabled. // applied to new_tm tcsetattr(STDIN_FILENO, TCSANOW, &new_tm); int ch; while(1){ ch = getchar(); if(ch == 'q' || ch == 'Q'){ break; }else if(ch == '\r'){//回车键 printf("down\n"); }else if(ch == '\33'){// ^[[A ^[[B ^[[C ^[[D ch = getchar(); if (ch == '['){ ch = getchar(); switch (ch) { case 'A': printf("up\n"); break; case 'B': printf("down\n"); break; case 'C': printf("right\n"); break; case 'D': printf("left\n"); break; default: break; } } } } // restore the original terminal settings. tcsetattr(STDIN_FILENO, 0, &old_tm); return 0; }
我打印出来的样子:
这是为什么?
2
收起
正在回答 回答被采纳积分+1
2回答
大白老师
1天前
#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>
#include <signal.h>
#include <termios.h>
{
key_control();
return 0;
}
#include <sys/time.h>
#include <stdlib.h>
#include <signal.h>
#include <termios.h>
//获取一个字符,不回显
int getch()
{
struct termios tm,tm_old;
//保存正常 输入属性 到 tm_old
tcgetattr(0,&tm_old);
//获取原始输入属性
cfmakeraw(&tm);
//设置原始输入属性
tcsetattr(0,0,&tm);
//不回显的获取一个字符
int ch = getchar();
//恢复正常输入属性
tcsetattr(0,0,&tm_old);
return ch;
}
void key_control()
{
int ch;
while(1){
ch = getch(); //^[
if(ch == 'q' || ch == 'Q'){
break;
}else if(ch == '\r'){//回车键
printf("down\n");
}else if(ch == '\33'){// ^[[A ^[[B ^[[C ^[[D
ch = getch(); //[
if(ch == '['){
ch = getch(); //A,B,C,D
switch(ch){
case 'A': //上
printf("up\n");
break;
case 'B': //下
printf("down\n");
break;
case 'C': //右
printf("right\n");
break;
case 'D': //左
printf("left\n");
break;
default:
break;
}
}
}
}
}
{
key_control();
return 0;
}
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星