- #1
The_Inventor
- 9
- 2
So I'm trying to teach myself C++ programming and I'm having trouble writing a password program.
Essentially I want to program to ask the user to input a password, and then compare that input with the correct password. If the user input matches the password I want the program to output a message saying "password accepted", if they do not match then I want the program to output a message saying "password invalid... Try again:" and from there the user continues to try a password until they input the correct password. This seemed simple at first however the problem arises when I try to introduce a while loop. If the password is incorrect after the second try they program continues to loop the message "password invalid...Try again:" without giving the user a chance to type in the password. Below is my source code, I'm using visual studio by the way. Can anyone help me out?
Essentially I want to program to ask the user to input a password, and then compare that input with the correct password. If the user input matches the password I want the program to output a message saying "password accepted", if they do not match then I want the program to output a message saying "password invalid... Try again:" and from there the user continues to try a password until they input the correct password. This seemed simple at first however the problem arises when I try to introduce a while loop. If the password is incorrect after the second try they program continues to loop the message "password invalid...Try again:" without giving the user a chance to type in the password. Below is my source code, I'm using visual studio by the way. Can anyone help me out?
C:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
string Admission()
{
string userinput; // this is the user's guess
string password = "TonyStark"; // this is the actual password
cout << "Enter password: ";
cin >> userinput;
if (userinput != password)
{
cout << "Password Invalid... Try Again: ";
cin >> userinput;
while (userinput != password)
cout << "Password Invalid... Try Again" << endl;
cin >> userinput;
}
else
cout << "Password Accepted... ";
return "Welcome";
}
int main()
{
cout << Admission() << endl;
system("pause>nul");
return 0;
}
Last edited by a moderator: