Replace input with “ * ” C++

前端 未结 4 886
春和景丽
春和景丽 2020-12-22 06:21

i want the user to input a passwort. of course it\'s a secret passwort so nobody should see it. so i tried to replace the letters and numbers the user inputs, with \' * \'.

相关标签:
4条回答
  • 2020-12-22 06:57

    as R. Martinho Fernandes says: strcpy doesn't do what you think it does.

    strcpy takes a char* buffer, and a char* source, and copies all of the data from the second (up to the first zero character) to the first. The easiest solution is to keep track of the length of pwstring and add characters one at a time:

    char pwstring[100];
    int length = 0;
    while ((pw=getch())!='x' && length < 99){
        cout << "*";
        pwstring[length] = pw;
        length = length + 1;
    }
    pwstring[length] = '\0';
    int pwint = atoi(pwstring);
    

    [EDIT] If pwstring is a std::string, then this becomes REALLY easy, since it already keeps track of it's own length.

    std::string pwstring;
    while ((pw=getch())!='x'){
        cout << "*";
        pwstring += pw;
    }
    int pwint = atoi(pwstring.c_str());
    
    0 讨论(0)
  • 2020-12-22 07:20

    On a posix system use getpass (3).

    It won't give you asterix echos, instead it echos nothing, but it is the way to do it.

    Or if you are on a BSD system you could use readpassphrase (3) which is more flexible than the older call.

    0 讨论(0)
  • 2020-12-22 07:22
    strcpy(pwstring,pw);
    

    I'm guessing that pwstring is a std::string? strcpy is a c function, it acts on 'c' null terminated strings. You are providing it with a c++ string and an int.

    0 讨论(0)
  • 2020-12-22 07:23

    Your question isn't as much about C++ as it is about how to interact with your terminal. The language is (deliberately) entirely agnostic of how input and output are handled, and everything that you're worried about is how the terminal behaves. As such, any answer will depend heavily on your platform and your terminal.

    In Linux, you will probably want to look into termios.h or ncurses.h. There's an old Posix function getpass() which does something similar to what you want, but it's deprecated.

    Unfortunately I have no idea how to approach terminal programming in Windows.

    0 讨论(0)
提交回复
热议问题