1

I am currently attempting to learn some basic C++ programming and decided to make myself a basic 3 attempt username and password checker to practice some of what I have read up on. Problem is when I run the program and enter an incorrect username and password first, the program will no longer recognize the correct username and password if entered on the second or third attempt. I have been looking at this for quite some time now and can't seem to get it to work. I have even included a currently commented out line to make sure that the program is reading the proper inputs, which it is.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int attempts=0;
    string username, password;
    while (attempts < 3)
    {
        cout<<"\nPlease enter your username and password seperated by a space.\n";
        getline( cin, username, ' ');
        cin>>password;
        if (username == "Ryan" && password == "pass")
        {
            cout<<"\nYou have been granted access.";
            return 0;
            cin.get();
        }
        else
        {
            attempts++;
            //cout<<username <<" " <<password << "\n";
            cout<<"Incorrect username or password, try again.";
            cout<<"\nAttempts remaining: "<<3-attempts <<"\n";
        }
    }
    cout<<"\nOut of attempts, access denied.";
    cin.get();

}

Any help or critique is greatly appreciated.

Ryan
  • 13
  • 3
  • 1
    Btw., the `return 0; cin.get();` in the `if` block makes no sense. A `return` is the end of the whole function, the `cin.get();` won´t get executed. – deviantfan May 24 '15 at 06:41
  • Yeah, I think that got left behind from early stages or something. Thanks for pointing it out though. I could definitely use to get in to the habit of going back and cleaning up after myself. – Ryan May 25 '15 at 07:12

1 Answers1

2

Your username includes a newline character '\n' after the first attempt due to getline

Changing your cin usage from

getline( cin, username, ' ');
cin>>password;

to

cin >> username;
cin >> password;

fixes your problem

RedAgito
  • 405
  • 2
  • 8
  • If you don't mind me asking then what dictates the program knowing to split the input at the space? I honestly didn't think it would split like that to be checked but instead would take the entire input and throw it in as the value of 'username'. – Ryan May 24 '15 at 06:51
  • It is standard behavior of the cin stream: it reads a string up to the first separator token, which is a blank – RedAgito May 24 '15 at 06:52
  • @Ryan The *extraction operator* `>>` splits input at spaces and newlines. It basically skips any initial spaces, then reads in until it meets another space and stops. – Galik May 24 '15 at 07:06