Well, here's my "conio.h" version for all to enjoy anyways...
Code:
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
#include <conio.h>
bool get_password(string &password,
char echo_char = '*', // echo character
bool esc_breaks = true, // does hitting ESC return false?
size_t limit_length = 0) // is there a length limit?
{
const int ESC = 27;
const int BACKSPACE = 8;
int c;
vector<char> input;
input.reserve(10);
// clear password
password.erase(password.begin(), password.end());
for (;;)
{
c = getch();
if (c == '\r')
{
input.push_back(0); // C-string terminator
password = &input[0];
break;
}//if
// only accept printable chars
if (isprint(c))
{
if ((limit_length == 0) ||
((limit_length != 0) && (input.size() < limit_length)))
{
input.push_back(c);
cout.put(echo_char);
}//if
else
{
cerr.put('\a');
}//else
}//if
// support for backspace functionality
if (c == BACKSPACE)
{
if (!input.empty())
{
cout.put(c); // backspace
cout.put(' '); // overwrite existing char
cout.put(c); // backspace back into position
input.pop_back();
}//if
else
{
cerr.put('\a');
}//else
}//if
if (esc_breaks && (c == ESC))
{
break;
}//if
}//for(;;)
return !password.empty();
}//get_password
int main()
{
string password;
cout << "Enter Password: " << flush;
if (get_password(password))
cout << "\nYou entered: " << password << endl;
else
cout << "\nNo password entered." << endl;
return 0;
}//main
gg