#include <cstdlib>
#include <iostream>
#include <curses.h>
usingnamespace std;
#define MAX_LENGHT 128
#define ENTER 10 // Bug? I tried #define ENTER KEY_ENTER but it didn't work...
#define BACKSPACE 8
int ch;
char password[MAX_LENGHT];
char *mypass="password";
int pos=0;
int main()
{
initscr();
noecho(); // turn off echoing
printw("Please enter the password:\n");
while(true)
{
ch=getch();
if(pos>=MAX_LENGHT) {cout<<'\a'; continue;} /* beep if password is too long */
if(ch==ENTER) break; /* User has pressed ENTER*/
elseif(ch==BACKSPACE) /* BACKSPACE was pressed*/
{
cout <<"\b \b";
password[--pos]='\0';
}
else/* A..Z a...z */
{
cout <<"*";
password[pos++]=ch;
password[pos]='\0';
}
if(pos<=0) pos=0;
}
if(strcmp(password,mypass)==0) printw("\nCorrect password!\n");
else printw("\nAccess denied\n");
echo(); // you can turn on echoing now
getch();
endwin();
return 0;
}
Notes:
1. Download curses here: http://sourceforge.net/projects/pdcurses/files/
2. You must link your project with pdcurses.lib library.
3. On widows pdcurses.dll must be in your program directory.
--------------
FIXME/CHECK: Does the second exaple work on linux?
Wouldn't that cause undefined behaviour? I thought you aren't allowed to close/open the standard IO stuff.
I don't know for Windows. UNIX systems have open() and close(); I've used them on stdin and stdout (but never stderr :P) before.
Interesting idea... But how will you open stdout? Where is it?
Again; I don't know how windows handles it; but on UNIX because you have file descriptors, stdin is 0, stdout is 1 and stderr is 2. Then you have the rest (up to 9 on sysv, up to 256 on Linux I think) to open other files.