Hide requested information

I want to hide what I request with one cin, for example I want to write a password and instead of show the characters i am using i want to show *. How can I do that?.

There is no way to do this with just the standard C++ library.
In windows you can use conio.h and _getch().
(I haven't run this code since I'm not on Windows.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

int main()
{
    string pw;
    for (int ch; (ch = _getch()) != '\n' && ch != EOF; )
    {
        pw.push_back(ch);
        cout << '*' << flush;
    }
    cout << '\n' << pw << '\n';
}

Last edited on
I think _getch() requires the carriage return to be first? Your code works once I use '\r' instead of '\n'. (This might just be MinGW-specific. There's probably a better way to do this using the Win32 API.)

________________________

Kinda hackish imo, but this also lets backspace work:
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
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

int main()
{
    string pw;
    for (int ch; (ch = _getch()) != '\r' && ch != EOF; )
    {
        if (ch == '\b')
        {
            if (pw.length() > 0)
            {
                pw.pop_back();
                cout << '\b' << ' ' << '\b' << flush;
            }
        }
        else
        {
            pw.push_back(ch);
            cout << '*' << flush;
        }
    }
    cout << "\nPassword: " << pw << '\n';
}

Again, probably is a better solution using Win32 API but I don't feel like looking that up right now.
Last edited on
Your code works once I use '\r' instead of '\n'

Good point.
In "raw mode" the '\r','\n' combo will not have been translated to just '\n'.
It would probably be a good idea to eat the '\n', too (one last _getch() after the loop).

I forgot all about backspacing.

There's probably a better way to do this using the Win32 API.
If you mean to avoid conio.h, I don't think that's necessary.
However, there may very well be an "enter string without echo" function somewhere.

I think this is a pretty decent solution. And it can be made portable by using ncurses instead of conio, although you may need to add a && ch != '\n' as well (but I'm not sure).
Last edited on
Topic archived. No new replies allowed.