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
|
#include <iostream>
#include <stdexcept>
#include <string>
#include <windows.h>
using namespace std;
string getpassword( const string& prompt = "Enter password> " )
{
string result;
// Set the console mode to no-echo, not-line-buffered input
DWORD mode, count;
HANDLE ih = GetStdHandle( STD_INPUT_HANDLE );
HANDLE oh = GetStdHandle( STD_OUTPUT_HANDLE );
if (!GetConsoleMode( ih, &mode ))
throw runtime_error(
"getpassword: You must be connected to a console to use this program.\n"
);
SetConsoleMode( ih, mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT) );
// Get the password string
WriteConsoleA( oh, prompt.c_str(), prompt.length(), &count, NULL );
char c;
while (ReadConsoleA( ih, &c, 1, &count, NULL) && (c != '\r') && (c != '\n'))
{
if (c == '\b')
{
if (result.length())
{
WriteConsoleA( oh, "\b \b", 3, &count, NULL );
result.erase( result.end() -1 );
}
}
else
{
WriteConsoleA( oh, "*", 1, &count, NULL );
result.push_back( c );
}
}
// Restore the console mode
SetConsoleMode( ih, mode );
return result;
}
int main()
{
try {
string password = getpassword( "Enter a test password> " );
cout << "\nYour password is " << password << endl;
}
catch (exception& e)
{
cerr << e.what();
return 1;
}
return 0;
}
| |