Capturing input without \n

醉酒当歌 提交于 2021-02-08 06:10:15

问题


I am making a simple 2d game in the terminal, and I have been wondering how I could get stdin without having to return. So, instead of the user having to press w\n (\n for return), they would just press 'w' and it would go forwards. scanf, gets, and getchar cannot do this, but I have seen it be done before in programs such as Vi. How would I achieve this?


回答1:


You need to set your terminal to non-canonical mode. You can use functions like tcsetattr, and tcgetattr to set and get terminal attributes. Here is a trivial example:

int main(int argc, const char *argv[])
{
    struct termios old, new;
    if (tcgetattr(fileno(stdin), &old) != 0) // get terminal attributes
        return 1;

    new = old;
    new.c_lflag &= ~ICANON; // turn off canonical bit.
    if (tcsetattr(fileno(stdin), TCSAFLUSH, &new) != 0) // set terminal attributes
        return 1;

    // at this point, you can read terminal without user needing to
    // press return

    tcsetattr(fileno(stdin), TCSAFLUSH, &old); // restore terminal when you are done.

    return 0;
}

For more info about these functions, see glibc documentation. Especially this part.



来源:https://stackoverflow.com/questions/10152381/capturing-input-without-n

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