如何在不等待新行的情况下在 C 中接受用户输入?
How can I take user input in C without waiting for a new line?
我试过使用 getch() 无济于事。我在 Rasbian linux 上使用 geany ide 和 gcc 编译器。我安装了 ncurses 库并正在使用它。
int input(){
int in;
in = getch();
printf("%i", in);
if(in == 'w'){
return 1;
}
else if(in == 's'){
return 0;
}
else{
return 3;
}
}
要使 getch()
正常工作,您需要在程序开始时初始化 ncurses。这是通过至少调用 initscr()
并禁用行缓冲,调用 cbreak()
来完成的。来自 cbreak man page:
Normally, the tty driver buffers typed characters until a newline or carriage return is typed. The cbreak routine disables line buffering and erase/kill character-processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program. The nocbreak routine returns the terminal to normal (cooked) mode.
Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly. Most interactive programs using curses set the cbreak mode. Note that cbreak overrides raw.
或者 cbreak()
,另一种禁用行缓冲的方法是通过 raw()
.
设置“原始模式”
有关在 ncurses 中读取键的完整示例,请参见实例
https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html
我试过使用 getch() 无济于事。我在 Rasbian linux 上使用 geany ide 和 gcc 编译器。我安装了 ncurses 库并正在使用它。
int input(){
int in;
in = getch();
printf("%i", in);
if(in == 'w'){
return 1;
}
else if(in == 's'){
return 0;
}
else{
return 3;
}
}
要使 getch()
正常工作,您需要在程序开始时初始化 ncurses。这是通过至少调用 initscr()
并禁用行缓冲,调用 cbreak()
来完成的。来自 cbreak man page:
Normally, the tty driver buffers typed characters until a newline or carriage return is typed. The cbreak routine disables line buffering and erase/kill character-processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program. The nocbreak routine returns the terminal to normal (cooked) mode.
Initially the terminal may or may not be in cbreak mode, as the mode is inherited; therefore, a program should call cbreak or nocbreak explicitly. Most interactive programs using curses set the cbreak mode. Note that cbreak overrides raw.
或者 cbreak()
,另一种禁用行缓冲的方法是通过 raw()
.
有关在 ncurses 中读取键的完整示例,请参见实例
https://tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html