Replace input with “ * ” C++

前端 未结 4 887
春和景丽
春和景丽 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());
    

提交回复
热议问题