There are two methods in which input can be taken in a more secure way:
- Do not display any content.
- Display a special character such as an asterisk instead of actual content.
In this method, input content will be invisible. This can be implemented in two ways:
using <windows.h>:
Program 1:
Below is the program where console mode is set to enable, echo input, and reset the console mode:
C++
#include <iostream>
#include <windows.h>
using namespace std;
std::string takePasswdFromUser()
{
HANDLE hStdInput
= GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdInput, &mode);
SetConsoleMode(
hStdInput,
mode & (~ENABLE_ECHO_INPUT));
string ipt;
getline(cin, ipt);
cout << endl;
SetConsoleMode(hStdInput, mode);
return ipt;
}
int main()
{
string input;
cout << "@root>>> " ;
input = takePasswdFromUser();
cout << input << endl;
}
|
Output:

For this getch() is used. This function takes a character input from user without buffer and doesn’t wait for the user to press “return” key.
Program 2:
Below is the C++ program to demonstrate the use of getch() in conio.h:
C++
#include <conio.h>
#include <iostream>
using namespace std;
std::string takePasswdFromUser()
{
string ipt = "" ;
char ipt_ch;
while ( true ) {
ipt_ch = getch();
if (ipt_ch < 32) {
cout << endl;
return ipt;
}
ipt.push_back(ipt_ch);
}
}
int main()
{
string input;
cout << "@root>>> " ;
input = takePasswdFromUser();
cout << input << endl;
}
|
Output:

Drawback: The user can’t clear the response made earlier. When backspace is pressed, the input is returned.
Program 3:
Below is the C++ program to demonstrate the solution to the above drawback:
C++
#include <conio.h>
#include <iostream>
using namespace std;
enum TT_Input {
BACKSPACE = 8,
RETURN = 32
};
std::string takePasswdFromUser()
{
string ipt = "" ;
char ipt_ch;
while ( true ) {
ipt_ch = getch();
if (ipt_ch < TT_Input::RETURN
&& ipt_ch != TT_Input::BACKSPACE) {
cout << endl;
return ipt;
}
if (ipt_ch == TT_Input::BACKSPACE) {
if (ipt.length() == 0)
continue ;
else {
ipt.pop_back();
continue ;
}
}
ipt.push_back(ipt_ch);
}
}
int main()
{
string input;
cout << "@root>>> " ;
input = takePasswdFromUser();
cout << input << endl;
}
|

Hiding the password by a special character(*):
The idea is to use the library <conio.h> here to hide password with asterisk(*). Below is the C++ program using conio.h to hide the password using *:
Program 4:
C++
#include <conio.h>
#include <iostream>
using namespace std;
enum IN {
IN_BACK = 8,
IN_RET = 13
};
std::string takePasswdFromUser(
char sp = '*' )
{
string passwd = "" ;
char ch_ipt;
while ( true ) {
ch_ipt = getch();
if (ch_ipt == IN::IN_RET) {
cout << endl;
return passwd;
}
else if (ch_ipt == IN::IN_BACK
&& passwd.length() != 0) {
passwd.pop_back();
cout << "\b \b" ;
continue ;
}
else if (ch_ipt == IN::IN_BACK
&& passwd.length() == 0) {
continue ;
}
passwd.push_back(ch_ipt);
cout << sp;
}
}
int main()
{
string input;
cout << "@root>>> " ;
input = takePasswdFromUser();
cout << input << endl;
}
|
