Replace input with “ * ” C++

2020-02-16 02:00发布

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 ' * '. here is my try.

while ((pw=getch())!='x'){
cout << "*";
strcpy(pwstring,pw);

}

input_pw=atoi(pwstring.c_str());

later i want the 'x' to be a 'enter'. but at the moment it's not important. with this, i get some compiler errors under Visual Studio.

Fehler  3   
error C2664: 'strcpy': Konvertierung des Parameters 1 von 'char' in 'char *' nicht möglich  c:\users\tim\desktop\kalssnne\methoden.h    zeile: 70

i will try to translate this.

error 3
error C2664: 'strcpy': converting of parameter 1 from 'char' to 'char*' is not possible.



  official english error code
    "'function' : cannot convert parameter number from 'type1' to 'type2'" 

thank u:  R. Martinho Fernandes

but what does this mean, and how can i fix it?

hope u can help me

greetings.

标签: c++ passwords
4条回答
爷、活的狠高调
2楼-- · 2020-02-16 02:28

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.

查看更多
Lonely孤独者°
3楼-- · 2020-02-16 02:29

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.

查看更多
神经病院院长
4楼-- · 2020-02-16 02:41
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.

查看更多
迷人小祖宗
5楼-- · 2020-02-16 02:46

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());
查看更多
登录 后发表回答