Escape sequences
Jul 5, 2011 at 7:29pm UTC
Hello,
I'm writing a function that masks password input but I can't figure out how to handle escape sequences properly. Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
#include <termios.h>
#include <unistd.h>
#include <stdexcept>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
string getpass(const char *prompt, bool show_asterisk=true )
{
const char BACKSPACE=127;
const char RETURN='\n' ;
string password;
unsigned int ch=0;
cout <<prompt<<endl;
struct termios tty_attr;
if (tcgetattr(STDIN_FILENO, &tty_attr) < 0)
throw runtime_error("tcgetattr error" );
tcflag_t c_lflag = tty_attr.c_lflag;
tty_attr.c_lflag &= ~ICANON;
tty_attr.c_lflag &= ~ECHO;
if (tcsetattr(STDIN_FILENO, 0, &tty_attr) < 0)
throw runtime_error("tcsetattr error" );
while ((ch=getchar())!=RETURN)
{
if (ch==BACKSPACE)
{
if (password.length()!=0)
{
if (show_asterisk)
cout <<"\b \b" ;
password.resize(password.length()-1);
}
}
else if (ch==27)
{
// ?
}
else
{
password+=ch;
if (show_asterisk)
cout <<'*' ;
}
}
tty_attr.c_lflag = c_lflag;
if (tcsetattr(STDIN_FILENO, 0, &tty_attr) < 0)
throw runtime_error("tcsetattr error" );
cout <<endl;
return password;
}
int main()
{
const char *correct_password="null" ;
string password=getpass("Please enter the password: " ,true );
// For debugging
for (int i=0;i<password.length();i++)
cout <<(int )password[i]<<' ' ;
cout <<endl;
if (password==correct_password)
cout <<"Correct password" <<endl;
else
cout <<"Incorrect password. Try again" <<endl;
return 0;
}
I know that the first character in a sequence will be 27(Esc). The problem is that I don't know how many non-printable character will follow it, eg. if I press
Esc - I get 27
Right Arrow: 27 91 67
F1..F12: 27 79 x
Delete: 27 91 51 126
So the number of characters returned is not the same.
Maybe there's another way around this?
Thanks for help.
Last edited on Jul 5, 2011 at 7:38pm UTC
Jul 7, 2011 at 1:23pm UTC
The best answer I ever saw about this subject is in a book written by Marc Rochkind entitled "Advanced C Programming for Displays." The ISBN is 0-13-010240-7 025. I don't know if it still in print, but this book has a great solution for handling the keyboard and its escape sequences.
Topic archived. No new replies allowed.