hi everyone, i need some help.
This is my problem.
When I input a string to the program, I want the screen console print out '*'.

ex:
string s;
cout<<"password :";
getline(cin,s);

when i type "abc123" for the password. The screen console will show "******".

I'm sorry about my poor english.

Recommended Answers

All 12 Replies

I don't know how to do this, so this wont be a great help but might get you started.

I recall seeing a similar question asked regarding windows programming and as I recall the API "SetConsoleMode" was used in the answer.

There is no standard C or C++ function/class that will do what you want. So you can resort to non-standard functions, for example the functions in conio.h if your compiler supports that header file and library.

Have youy searched google for password code? like this link?

Another example here

It is simple enough to write your own function to do this. Pass in the password to the function, and have it generate a string of '*' characters of the same length that it returns. Call this function string obfuscatePswd(const string& pswd). Then your code becomes this: cout << obfuscatePswd(password) << " :";

That's easy enough, but the problem is getting the string from the keyboard without actually displaying the plain text, display stars instead of the text.

Perhaps it's possible to implement some sort of low level keyboard hook to capture the input but print "*".

i think i will use _getch().
if _getch()!='\n' i will cout<<"*";
but i can't backspace if i type wrong pass

Here's how to backspace

int main()
{
    int c;
    while ((c = _getch()) != '\n')
    {
        if (c == '\b')
            putchar(c);
        else
            putchar('*');
    }
    return 0;
}
Member Avatar for iamthwee

This is not possible. It is OS dependant

what is not possible??

Member Avatar for iamthwee

Sorry I worded it wrong. I meant in c++, as what he is asking for is OS dependant. Clearly, depending on your OS you can do this.

i used this

char* s1 = new char[100];
char y = _getch();
s1[0] = y;
int i = 0;

while (s1[i] != 13)
    {
        cout << '*';
        i++;
        y = _getch();
        s1[i] = y;
    }
s1[i] = '\0';

Pass = s1;
delete []s1;

but it is not perfect

Didn't you read this post to show how to backspace?

line 16: if Pass in line 15 is a pointer then you can't delete s1 on line 16 because it will invalidate Pass also.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.