-4

I'm doing a simple program that is finding the username and password in a text file. Originally when i wrote the program it ran fine, however, now I am getting "String subscript out of range errors" and I am not really sure why. Any help I could get would be great.

Here is my code:

string username, password, pwCheck;
ifstream adminIn; 
adminIn.open("admin.txt");

cout << "\n\nAdmin and Librarian Login\n\n";

cout << "Username:  ";
cin >> username;

cout << "Password:  ";
cin >> password;

bool isFound = false;
while (!adminIn.eof())
{
    string temp = "";
    for (int i = 0; i < username.size(); i++)
    {
        if (temp[i] == username[i])
        {
            isFound = true;
        }
        else
        {
            isFound = false;
        }
    }

    if (isFound)
    {
        for (int i = username.size() + 1; i < temp.size(); i++)
        {
            pwCheck = pwCheck + temp[i];
        }
    }

}
Camilo Terevinto
  • 26,697
  • 6
  • 67
  • 99
  • https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –  Apr 21 '18 at 20:41
  • 2
    Because you access `temp[i]` of an empty string. – Quimby Apr 21 '18 at 20:43
  • Use a debugger and step through the code. It's never too early to learn how to use one, and it's one of the most valuable tools in a coder''s toolbox. You could have found the problem yourself easily doing so. – Ken White Apr 21 '18 at 20:47
  • You're never reading anything from the file. – Barmar Apr 21 '18 at 20:48
  • Probably `temp` is suppose to hold the line you read from the file, but you never do that. – Barmar Apr 21 '18 at 20:49
  • And how exactly do you expect `string temp = "";` followed two lines later by `temp[i]` is going to work anyway? Even more important than using a debugger is learning to actually read and understand the code you're writing. – Ken White Apr 21 '18 at 20:49
  • There's no reason to loop over the characters in `username`. Just compare the strings: `if (username == temp)`. – Barmar Apr 21 '18 at 20:49

1 Answers1

0

You do not do really read from a file. Use construction like

string line;

getline (adminIn, line);

and then search username and password in that line

Vitaliy
  • 28
  • 4