Creating a text file with a certain string and using it to compare in the future

37 Views Asked by At

I want to create a text file for first run carrying the password and use the code to check the entire string for the password entered previously. The current code returns true value for the 1st few alphabets even if the whole password isn`t entered.

    int Manager::ManagerView1()
   {
    Passwordsearch:
    system("cls");
    string search;
    int offset,ErrorVar;
    string line;
    ifstream Myfile;
    Myfile.open("Password.txt");

    cout << "Enter your Password :\n";
    cin >> search;
    if (Myfile.is_open())
    {
        while (!Myfile.eof())
    {
        getline(Myfile,line);
        if ((offset = line.find(search, 0)) != string::npos)
        {
            cout << "Password Accepted ..\n";
            system("pause");
        }
        else
        {
            cout << "Password Incorrect. \nPress\n 1.) Go back to the main     screen\n 2.) Re-Enter Password \n";
            cin >> ErrorVar;
            if (ErrorVar == 1)
            {
                system("PAUSE");
                return 1;
            }
            else if (ErrorVar == 2)
            {
                system("PAUSE");
                system("cls");
                goto Passwordsearch;
            }
            else
            {
                cout << "Wrong option !! Please try again\n";
                system("PAUSE");
                return 1;
            }
        }
      }
      }
      }

This is the password file that i want to check the string from: enter image description here

2

There are 2 best solutions below

11
Some programmer dude On

Your problem is because of how the find function works. It looks for the sub-string contained in search.

You have to extract the complete password from the file, and then compare using equality instead of just searching for a sub-string.

0
lowarago On

When you use string.find(param1, param2) it just tells you if a string in this case "Anonymous" does contain text you put as a first paramater inside find() function.

If you want to avoid that you shouldn't be using *find()* at all. Instead, you should do comparing.

First you read the string from txt file and store it in a string line. Then you ask user to enter password after he enters password, you check if your string line is eqaul to password .

std::string my_pass = "Anonymous";//Get it from file.
std::string input_pass = "";
std::cin >> input_pass;

if(input_pass==my_pass){
    std::cout << "PASSWORD CORRECT\n";
}