忽略stdin的退格键

我想创建一个程序,强制它的用户输入文本,但不允许他删除任何一个,在C中这样做的简单方法是什么?

我唯一得到的是(c = getchar()) != EOF && c != '\b'哪个不起作用。 有任何想法吗?

POSIX – unix版本

 #include  #include  #include  #include  int main() { int fd=fileno(stdin); struct termios oldtio,newtio; tcgetattr(fd,&oldtio); /* save current settings */ memcpy(&newtio, &oldtio, sizeof(oldtio)); newtio.c_lflag = ICANON; newtio.c_cc[VERASE] = 0; /* turn off del */ tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); /* process user input here */ tcsetattr(fd,TCSANOW,&oldtio); /* restore setting */ return 0; } 

您无法使用可移植代码 – 基本上每个操作系统都在标准输入流中内置了某种最小的缓冲/编辑。

根据您需要定位的操作系统,有一个很好的改变,你将有一个可用于无缓冲读取的getch 。 在Windows上,您包含并继续操作。 在大多数Unix上,你需要为它包含(和链接)curses(或ncurses)。

这可能比你想象的要复杂得多。 要做到这一点,你可能需要接管控制用户输入的字符。

看看curses库。 wgetch函数应该是你需要的,但首先你需要初始化curses等。阅读手册页 – 如果你很幸运,你会找到ncurses或curses -intro手册页。 这是一个片段:

  To initialize the routines, the routine initscr or newterm must be called before any of the other routines that deal with windows and screens are used. The routine endwin must be called before exiting. To get character-at-a-time input without echoing (most interactive, screen oriented programs want this), the following sequence should be used: initscr(); cbreak(); noecho(); Most programs would additionally use the sequence: nonl(); intrflush(stdscr, FALSE); keypad(stdscr, TRUE); 

如果您没有该联机帮助页/获取更多信息,请查看各个函数手册页。