cparks10
cparks10

Reputation: 377

C++ File Input Stream looping issue

Working on a C++ program. Wanting to make a username "checker". Processing the ifstream in a while loop. The problem I am having is that if the user name does not exist, then it is printing the error message each time for the amount of lines in the text. I know that the problem is in the while loop. I do not know how to give the error message without checking the file for the user name. Any help would be greatly appreciated. Thanks!

string username;
string password;
int input;

bool keepGoing;
while (keepGoing){

cout<<("1.Login\n2.Create Username and Password\n3.Exit")<<endl;


cin>>input;
///////////////////////////////////////////////////////////
        if(input == 1){ //LOGIN!!!
        //open the file
        ifstream user("userinfo.txt");

    if(user.is_open()){
    //get the username
    string checkUser;
    string checkPass;
    cout<<"Enter username: "<<endl;
    cin>>checkUser;
    //create a variable to store existing username
    //Iterate throught the text file, and log them in if thier info is correct
    //while(user>>username>>password){
    while(getline(user, username)){
        //if the name is there
        if (checkUser != username){
            cout<<"Username not here!"<<endl;
        }
        if (checkUser==username){
            //cout<<"Welcome back, "<<username<<endl;
            cout<<"Password: "<<endl;
            cin>>checkPass;//get user input
                if(checkPass==password){//if the password is correct
                    cout<<"Welcome back, "<<username<<endl;//User is logged in
                    //put in the menu 2 function
                }else if(checkPass!=password){//If pass is incorrect
                    cout<<"Password incorrect."<<endl;//Denied
                }//end else if
            }//end if
    }//end while loop
   }
   else{
    cout<<"Unable to open file"<<endl;

     }
    }

Upvotes: 0

Views: 457

Answers (2)

Daniel Kovachev
Daniel Kovachev

Reputation: 147

you should extract the logic of checking user name into a function which will return true on sucsses and false on failure.

bool checkUser(const std::string& username, const std::string& pass){
//check if user exists
while(getline()){
if(username == somthing)
{
    if(pass == somthing){
       return true;
    }
    std::cout << "incorrect pass";
    return false;
}
}
//if you reached here than the username doesnt exists
return false;
}

Upvotes: 1

SaschaP
SaschaP

Reputation: 889

just do it like this

bool foundUser = false;
while(getline(user, username)) {

    if(checkUser == username) {
        foundUser = true;
        break;
    }
}
if(foundUser) {
    // check password here
}
else {
    // display error message
}

Upvotes: 2

Related Questions