繁体   English   中英

如何制作一个从文件中读取密码的c ++程序,并与用户编写的密码进行比较

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

我正在尝试创建一个受密码保护的程序。我必须从文件中读取密码,并与运行程序时写入的密码进行比较。从键盘写入的密码必须使用ASTERIX加密。 这就是我现在所做的:

#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();
        }

   }
}

我建议创建一个std::string来将每个char存储在一个变量中。 它可能会是这样的:

#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;
     }
}

如果while循环不起作用,我建议在文件的密码末尾写一个额外的唯一字符(类似于$)并执行类似: while(currentCharacter != '$')然后执行currentCharacter = file.get() while循环开头的currentCharacter = file.get()以及事先的do语句而不是我放的东西:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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