简体   繁体   中英

How to make a c++ program that read a password from a file and compare with the password written by user

I m trying to make a password protected program.My password must be read from a file and compare with the password written when you run the program.The password written from keyboard must be encrypted with ASTERIX. This is what I've done by now:

#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <string>
using namespace std;
void main()
{
    char pass[20], mypass[20], ch;
    cout << "Enter the password: " << endl;
    int i=0;
    do
    {
        ch=cin.get();
        pass[i]=ch;
        if (ch!=27 && ch!=13 && ch!=9)
            putchar('*');
        else
            break;
        i++;
    } while (i<19);
    pass[i]='\0';
    ifstream myfile("password.txt");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {

            if (strcmp(pass, mypass)!=0)
            {
                cout << "Incorrect password." << endl;
            }

            myfile.close();
        }

   }
}

I would suggest making a std::string to store each char in one variable. It might go something like this:

#include <string>
void main(){
     std::string storedPassword, userEntered;
     char currentCharacter;
     ifstream file("password.txt");
     while(currentCharacter << file){
          storedPassword.append(currentCharacter);
     }
     std::cout << "Enter the password: ";
     std::cin >> userEntered;
     if(userEntered == storedPassword){
          std::cout << "\nThat is the correct password!" << std::endl;
     } else {
          std::cout << "That is incorrect." << std::endl;
     }
}

If the while loop doesn't work, I'd suggest writing an extra unique character at the end of the password in the file (something like $) and doing something like: while(currentCharacter != '$') and then doing currentCharacter = file.get() at the beginning of the while loop as well as in a do statement beforehand rather than what I had put:

do{
currentCharacter = file.get();
}
while(currentCharacter != '$'){
//do everything above and put: currentCharacter = file.get(); at the end of the loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM