-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHide_Password_at_console.cpp
More file actions
58 lines (53 loc) · 1.35 KB
/
Hide_Password_at_console.cpp
File metadata and controls
58 lines (53 loc) · 1.35 KB
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
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int getch() {
int ch;
struct termios t_old, t_new;
tcgetattr(STDIN_FILENO, &t_old);
t_new = t_old;
t_new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &t_new);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &t_old);
return ch;
}
string getpass(const char *prompt, bool show_asterisk = true) {
const char BACKSPACE = 127;
const char RETURN = 10;
string password;
unsigned char ch = 0;
cout << prompt << endl;
while((ch = getch()) != RETURN) {
if(ch == BACKSPACE) {
if(password.length() != 0) {
if(show_asterisk)
cout << "\b \b";
password.resize(password.length() - 1);
}
}
else {
password += ch;
if(show_asterisk)
cout << '*';
}
}
cout << endl;
return password;
}
int main() {
const char *correct_password = "hello_world";
while (1) {
string password = getpass("Please enter the password: ", true); // Show asterisks, false:to show nothing
if(password == correct_password) {
cout << "Correct password" << endl;
break;
} else {
cout << "Incorrect password. Try again" << endl;
}
}
return 0;
}