trouble with while loops

Hi everyone, Im having a bit of trouble with while loops...this program should ask the user for their name, if incorrect it should send an error msg and ask for input again...after the correct name is entered the program should prompt the user to enter a password, again if incorrect it should send an error msg and ask for input again.

the code below does what it should when asking for a name..HOWEVER it does not allow the user to enter a password and instead jumps straight to the error msg..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<string>
#include<iomanip>

using namespace std;

int main()
{
// Variables
string username;
string password;

//Intro: Welcome User
cout << " Hello and welcome to the prestigious Bank of Kwantlen" << endl;
cout << " Enter your name: ";
cin >> username;

while ((username != "sadia") && (username != "rajput"))
{
cout << " Sorry that is incorrect. Please enter your name:";
cin >> username;
}

cout << " Welcome, Sadia Rajput." << endl;
cout << " To continue, enter your password: ";


(THIS IS WHERE THE PROBLEM IS..DOES NOT LET ME ENTER A PASSWORD, EXECUTES WHILE LOOP RIGHT AWAY)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cin >> password;


while (password != "yaycplusplus")
{
cout << "That is incorrect, enter password: ";
cin >> password;
}

cout << "You have been successfully authenticated. You are accessing membership number 100247817" << endl;

system("pause");
return 0;
}

after the correct name is entered, the program displays this:

"Welcome, Sadia Rajput."
"To continue, enter your password: That is incorrect, enter password: "

Any help is greatly appreciated, i would prefer to do this using the while loops and not bool statements
The problem is that it seems you enter two names in the first request. For example you enter

sadia rajput

but the statement

cin >> username;

accepts only one name that is the first one. The second name will be as before in the input buffer. So the next time when you think that you are entering the password the stream reads the name kept in the input buffer.

Substitute statement

cin >> username;


for

std::getline( std::cin, username );

and also chamge the condition of the loop because you will need to compare the full name.
Last edited on
To make life easier i just ended up taking out the 'whitespace' from the string variable username

Thank you for you help! It's greatly appreciated =)
Topic archived. No new replies allowed.