Search code examples
c++windowspasswordscodeblocksclion

How to display asterisk for input password in C++ using CLion


There is a lot of sample code online for a password program that hides the input with an asterisk. These programs work when I compile them with my CodeBlocks IDE by outputting a * everytime I type in a letter.

Enter Password  : ******
You entered : iiiiii
Process returned 0 (0x0)   execution time : 6.860 s
Press any key to continue.

However, when I use the CLion IDE, I can see the letters I type:

Enter Password  :iiiiii
 ******
You entered : iiiiii
Process finished with exit code 0

Can someone explain why this difference exists between the two IDEs?

The code that I am using (I found it online) is:

#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std; //needed for cout and etc

int main()
{
    START:
    system("cls");
    cout<<"\nEnter Password  : ";
    char pass[32];//to store password.
    int i = 0;
    char a;//a Temp char
    for(i=0;;)//infinite loop
    {
        a=getch();//stores char typed in a
        if((a>='a'&&a<='z')||(a>='A'&&a<='Z')||(a>='0'&&a<='9'))
            //check if a is numeric or alphabet
        {
            pass[i]=a;//stores a in pass
            ++i;
            cout<<"*";
        }
        if(a=='\b'&&i>=1)//if user typed backspace
            //i should be greater than 1.
        {
            cout<<"\b \b";//rub the character behind the cursor.
            --i;
        }
        if(a=='\r')//if enter is pressed
        {
            pass[i]='\0';//null means end of string.
            break;//break the loop
        }
    }
    cout<<"\nYou entered : "<<pass;
    //here we can even check for minimum digits needed
    if(i<=5)
    {
        cout<<"\nMinimum 6 digits needed.\nEnter Again";
        getch();//It was not pausing :p
        goto START;
    }
    return 0;
}
//Lets check for errors.
//You can even put file system.

I know that there are a lot of questions similar to this one, however, none of them could explain why it is not working when using the CLion IDE.


Solution

  • Maybe

    #include <conio.h>
    
    int main()
    {
        char s[10] = { 0 };
        int i;
        for (i = 0; i < 10;i++) {
            s[i] = _getch(); _putch('*');
            if (s[i] == 13) break;
        };
        printf("\nYour pass is %s", s);
        getchar();
        return 0;
    }