ユーザーにテキストの入力を強制するが、それを消去することを許可しないプログラムを作成したいのですが、C でそれを行う簡単な方法は何ですか?
私が持っている唯一のものは(c = getchar()) != EOF && c != '\b'
、うまくいかないことです。何か案は?
POSIX - UNIX 版
#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;
}
移植可能なコードではできません。基本的にすべての OS には、標準入力ストリームに最小限のバッファリング/編集が組み込まれています。
ターゲットにする必要がある OS によっては、getch
バッファなしの読み取りを行う適切な変更が利用可能になります。Windowsでは、それを含め<conio.h>
て実行します。ほとんどの Unix では、curses (または ncurses) を含める (およびリンクする) 必要があります。
これはおそらく想像以上に複雑です。これを行うには、おそらく、ユーザーが入力している文字のエコーなどの制御を引き継ぐ必要があります。
curses ライブラリを見てください。wgetch 関数は必要なものであるはずですが、最初に curses などを初期化する必要があります。man ページを読んでください。運が良ければ、ncurses または curses-intro の man ページを見つけることができます。ここにスニペットがあります:
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);
そのマンページを持っていない場合、または詳細については、個々の関数のマンページを調べてください。