我正在尝试在Linux上通过终端上的gcc使用getche

问题描述

|| 我需要知道如何使用getche()函数在C中编译程序,但是由于需要引用,所以没有编译。有人知道缺少什么参考吗? 即时通讯使用此命令: gcc filename.c -o执行     

解决方法

        对于Linux和其他Unix平台,您可能希望使用ncurses而不是仅尝试模拟getch [e]。它是一个稍微复杂的API,但是它将为您处理各种陷阱,而Dan D.发布的简单模拟将不会。 (例如,如果用户键入^ C或^ Z,它将执行Right Thing。)     ,        从http://wesley.vidiqatch.org/code-snippets/alternative-for-getch-and-getche-on-linux/
/*
    getch() and getche() functionality for UNIX,based on termios (terminal handling functions)

    This code snippet was written by Wesley Stessens (wesley@ubuntu.com)
    It is released in the Public Domain.
*/

#include <termios.h>
#include <stdio.h>

static struct termios old,new;

/* Initialize new terminal i/o settings */
void initTermios(int echo) {
    tcgetattr(0,&old); /* grab old terminal i/o settings */
    new = old; /* make new settings same as old settings */
    new.c_lflag &= ~ICANON; /* disable buffered i/o */
    new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
    tcsetattr(0,TCSANOW,&new); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) {
    tcsetattr(0,&old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) {
    char ch;
    initTermios(echo);
    ch = getchar();
    resetTermios();
    return ch;
}

/* Read 1 character without echo */
char getch(void) {
    return getch_(0);
}

/* Read 1 character with echo */
char getche(void) {
    return getch_(1);
}

/* Let\'s test it out */
int main(void) {
    char c;
    printf(\"(getche example) please type a letter: \");
    c = getche();
    printf(\"\\nYou typed: %c\\n\",c);
    printf(\"(getch example) please type a letter...\");
    c = getch();
    printf(\"\\nYou typed: %c\\n\",c);
    return 0;
}