ssgfanboy
ssgfanboy

Reputation: 63

Bool result returns false after reading data from a file

I am trying to learn more about C++ and was given the task of validating a login.

So far I have

#include <iostream>
#include <istream>
#include <fstream>
#include <string>
using namespace std;

void getLogin(string & userName, int password);
bool validateLogin(string userName, int password);
void showResult(bool validation);

int main()
{
    int password = 0;
    string userName;
    bool validation;

    getLogin(userName, password);
    validation = validateLogin(userName, password);
    showResult(validation);

    return 0;
}

void getLogin(string & userName, int password)
{
    cout << "Enter your ID:  ";
    cin >> userName;
    cout << "Enter your PW:  ";
    cin >> password;
}

bool validateLogin(string userName, int password)
{
    string user;
    int pass;
    ifstream inFile;
    inFile.open("C:\\login.txt");
    if (inFile.fail())
    {
        cout << "Error finding file";
        exit(1);
    }
    getline(inFile, user);
    inFile >> pass;

    if (userName == user && password == pass)
    {
        return true;
    }
    else
    {
        return false;
    }
}

void showResult(bool validation)
{
    if (validation == true)
    {
        cout << "Valid\n\n";
    }
    else
    {
        cout << "Invalid\n\n";
    }
}

Inside the login.txt file, the username and password are already written. The prompt asks for the user to enter in their username and password. When I enter in the username and password that are inside the txt file, it always shows as invalid. Link to output and login.txt

Upvotes: 0

Views: 97

Answers (1)

clstrfsck
clstrfsck

Reputation: 14837

Assuming you really do want to use an int as a password, the problem is in this function declaration and definition:

void getLogin(string & userName, int password);

Change the password parameter to a reference, similar to the userName parameter and all should be fine. Change the declaration to:

void getLogin(string & userName, int & password);

Then change the definition to match.

Upvotes: 1

Related Questions