0

I wonder if there is any code to make what you type (ex. Hello becomes *****) becomes unreadeble.

i have this code

string pass;

When you type in for the "cin" i dont want any one to be able to read it.

cin >> pass;
cout << pass;
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Winne
  • 11
  • 1

2 Answers2

0

Here we are masking input with asterisk. We use tcgetattr/tcsetattr to get and set terminal attributes so echo is disabled on stdin and we print "*" instead on each character user input.

#include <iostream>
#include <string>
#include <termios.h>
#include <stdio.h>

int getch() {
    struct termios oldtc, newtc;
    int ch;
    tcgetattr(STDIN_FILENO, &oldtc);
    newtc = oldtc;
    newtc.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
    ch=getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
    return ch;
}


int main(int argc, char **argv) {

    int ch;
    printf("Press ENTER to exit.\n\n");

    for (;;) {

        ch = getch();

        if(ch == '\n')
              break;
        printf("*");
    }

    return 0;
}
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

The code below is tested and runnable on Visual Studio 2012 (also VC6.0). Visit http://msdn.microsoft.com/en-us/library/aa297934%28v=vs.60%29.aspx for more information about function _getch().

_getch(): Get a character from the console without echo (_getch) or with echo (_getche).

#include <iostream>
#include <string>
#include <conio.h>

int main()
{
    std::string pass;
    for(int c; c = _getch(); ){
        if(c=='\r' || c=='\n' || c==EOF){
            break;
        }else{
            pass += c;
            std::cout << '*';
        }
    }

    std::cout << "\nYour password is: " << pass << std::endl;
    return 0;
}
Peach
  • 87
  • 1
  • 14