Writing a function to read a password from the console
Jun 9, 2011 at 3:36am UTC
Hello, I am trying to write a function that reads a password. The function hides the characters (with an asterisk) and stores them in a std::string.
Here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
std::string GetPassword() {
std::string pass;
char read;
while ( (read = getch()) != '\n' ) {
if ( isalnum(read) || read == ' ' ) {
putch('*' );
pass.append(&read);
}
else if ( read == '\b' ) {
if ( pass.length() > 0 ) {
printf("\b\b" );
pass = pass.substr(0, pass.length()-1);
}
}
}
return pass;
}
It requires conio.h, cstdio (stdio.h) and cstdlib (stdlib.h)
The problem is that it does not read anything or write any asterisks to the terminal.
Jun 9, 2011 at 8:07am UTC
failbit it works incorrect here < pass.append(&read) >....try to print pass and you'll see unknown symbols.......it works correct when you pass std::string to append or char*.....
Topic archived. No new replies allowed.