Making terminal input send after a certain number of characters

你。 提交于 2019-12-22 16:35:08

问题


I am creating a Linux terminal program using C.

I am trying to make a two digit code address a array location. I don't want to have to hit enter after every two digit input, I want the input to just be sent to my buffer variable through scanf directly after to characters are entered.

I do not have a code sample, as i have no idea how to approach this.

Thanks for any help!


回答1:


You've got two options, which solve the same problem in nearly the same way. The first is to use stdbuf when you run your program; the invocation is:

 stdbuf -i0 ./a.out

Using that prevents stdin from being line-buffered, and will let you use fread() or similar commands to retrieve input as it happens.

The other is to put the terminal in raw mode. It's well-described here. But the downside is that control characters are no longer dealt with. In your program, you

#include <termios.h> 

main(){
    struct termios trm;

    tcgetattr(STDIN_FILENO, &trm); /* get the current settings */
    trm.c_cc[VMIN] = 1;     /* return after 1 byte read; you might make this a 2*/
    trm.c_cc[VTIME] = 0;    /* block forever until 1 byte is read */
    tcsetattr(STDIN_FILENO, TCSANOW, &trm); 
}


来源:https://stackoverflow.com/questions/9186036/making-terminal-input-send-after-a-certain-number-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!