我发现了conio.h的getch()的c实现。可悲的是它带有一个转换警告编译,我不知道该怎么做才能正确解决它。
我找到了this链接,但是我不知道如何实现它。
#include<termios.h>
#include<unistd.h>
#include<stdio.h>
#include"getch.h"
/* reads from keypress, doesn't echo */
int getch(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
/* reads from keypress, echoes */
int getche(void)
{
struct termios oldattr, newattr;
int ch;
tcgetattr( STDIN_FILENO, &oldattr );
newattr = oldattr;
newattr.c_lflag &= ~( ICANON );
tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
CLANG 3.5返回:
getch.c:13:24: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
newattr.c_lflag &= ~( ICANON | ECHO );
~~ ^~~~~~~~~~~~~~~~~~
getch.c:27:24: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
newattr.c_lflag &= ~( ICANON );
~~ ^~~~~~~~~~~
2 warnings generated.
最佳答案
由于整数提升,这些定义提升为int,但c_lflag成员是无符号整数。
确保按无符号类型完成按位操作:
newattr.c_lflag &= ~( 0u | ICANON | ECHO );
^