You are here:

C/looping

Advertisement


Question
Hello, I first wanted to say thank you for looking at this.
My issue is that I'm new and learning basic concepts.  I'm trying to build a simple program that asks for a username and password (being able to accept multiple usernames/passwords).  The issue I'm running in to is having it reprompt the user to reinput the username/password when incorrect.  I've gotten it to work with a single username/password combo but when if a second username/password combo is used, it just continues to reprompt until the first one is recognized.  Here's my code:

#include <iostream>
#include <string>

using namespace std;

int main ()
{
   string username;
   string password;

   cout << "Please enter username: \n";
   cin >> username;

   cout << "Please enter password: \n";
   cin >> password;

   if
      (username == "root" && password == "pas7")
   {cout << "Access Granted!\n";
   }
   else if
       (username == "root2" && password == "pas6")
   {
       cout << "Access Granted!\n";
   }
   else
   {
       cout << "Access Denied!\n";
   }
   while ((username != "root" && password != "pas7") || (username != "root2" && password != "pas6"))
   {
       cout << "Please enter username: \n";
       cin >> username;

       cout << "Please enter password: \n";
       cin >> password;
   }

}

Answer
Hi Andrew,

I don't have an IDE handy, but you could try something like this -

int main ()
{
string username;
string password;
bool status = false;

while (!status)
{
  cout << "Please enter username: \n";
  cin >> username;

  cout << "Please enter password: \n";
  cin >> password;
  if ((username == "root" && pwd == "pas7"))
  {
     status = true;
     break;
  }
  if ((username == "root2" && pwd == "pas6"))
  {
     status = true;
     break;
  }
  cout << "Access Denied!\n";
}
cout << "Access Granted!\n";
cin >>;
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Kaustav Neogy

Expertise

i can answer queries related to general programming constructs in C.

Experience

i have been programming in c since 1998.

©2016 About.com. All rights reserved.