Ignore backspace key from stdin

こ雲淡風輕ζ 提交于 2019-12-19 03:16:13

问题


I want to make a program that forces it's user to input text but doesn't allow him to erase any of it, what's a simple way of doing it in C?

The only thing I've got is (c = getchar()) != EOF && c != '\b' which doesn't work. Any ideas?


回答1:


POSIX - unix version

#include <sys/types.h>        
#include <termios.h>
#include <stdio.h>
#include <string.h>

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;        
}



回答2:


You can't do it with portable code -- essentially every OS has some sort of minimal buffering/editing built into the standard input stream.

Depending on the OSes you need to target, there's a good change you'll have a getch available that will do unbuffered reading. On Windows, you include <conio.h> and go for it. On most Unix, you'll need to include (and link to) curses (or ncurses) for it.




回答3:


This is likely more complicated than you imagine. To do this, you'll presumably need to take over control of echoing the characters the user is typing etc.

Have a look at the curses library. The wgetch function should be what you need, but first you'll need to initialise curses etc. Have a read of the man pages - if you're lucky you'll find ncurses or curses-intro man pages. Here's a snippet:

   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);

If you've not got that manpage / for further info, look up the individual function man pages.



来源:https://stackoverflow.com/questions/3167733/ignore-backspace-key-from-stdin

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