Ignore backspace key from stdin

2020-03-03 08:18发布

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?

3条回答
beautiful°
2楼-- · 2020-03-03 08:33

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.

查看更多
手持菜刀,她持情操
3楼-- · 2020-03-03 08:36

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;        
}
查看更多
Explosion°爆炸
4楼-- · 2020-03-03 08:46

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.

查看更多
登录 后发表回答