Question

I'm making a software as an ATM, so when the user try to enter the password the user only sees *******, but when trying to delete it doesn't delete a character. It just adds a new one. Here's my code:

string password2 = "";

cout << "PASSWORD: ";

ch = _getch(); 
while(ch != 13) //character 13 is enter
{
   password2.push_back(ch);
   cout << '*';
   ch = _getch();
}

And also, I try to use pop_back(); but it doesn't work either. Can anybody help me please?

Was it helpful?

Solution

Just did a little magic and created this: I must admit, I don't like the style... But it "works" !

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

bool verify_pass(const std::string& pass)
{
    std::string input = "";
    char ch = '0';
    while(true)
    {
        ch = getch();
        if(ch == '\b')
        {
            if(input.size() > 0)
            {
                input.erase(input.begin() + input.size() - 1);  // erase last char
                std::cout << "\b \b";
            }
        }
        else if(ch != '\r\n' && ch != '\n' && ch != '\r')
        {
            input += ch;
            std::cout << '*';
        }
        else
            break;
    }
    return input == pass;
}

int main()
{
    std::string insecurePass = "1234";
    std::cout << "Enter Password: ";

    if(verify_pass(insecurePass))
        std::cout << "\nCorrect!\n";
    else
        std::cout << "\nFalse!\n";

}

By the way, you can use the vector like I used the string, but use push_back instead of += and pop_back() should work too instead of my method with erase.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top