I need help writing a program that allows the user to input a 4 digit password. The correct password is hard coded "1234", after 3 incorrect attempts it should display " the phone is locked" and break. Please help with my while loop and elif!
#include <iostream>
using namespace std;
int main()
{
char response;
int passcode = 1234;
int input;
int lock = 3;
int limit = 0;
cout << "Welcome user!" << endl;
cout << " Please enter your passcode: " << endl;
cin >> passcode;
if (passcode == input)
{
cout << "Password was correct, Welcome!" << endl;
}
else if
{
while (passcode != input)
cout << " Incorrect passcode, You have " << lock-- << "Trys remaining" << endl;
if (lock == 0)
cout << " Too many tries mother. " << endl;
break;
}
cin >> response;
return 0;
You have a small mistake on the cin >> part, you want the int passcode = 1234 not to change and you have set cin >> passcode, which after the user enters the passcode will change the value of passcode, and then it will be messed up which will make the program malfunction. Here's the fix
#include <iostream>
usingnamespace std;
int main()
{
char response;
int passcode = 1234;
int input;
int lock = 3;
int limit = 0;
cout << "Welcome user!" << endl;
cout << " Please enter your passcode: " << endl;
cin >> input;
if (input == passcode)
{
cout << "Password was correct, Welcome!" << endl;
}
elseif
{
while (input != passcode)
cout << " Incorrect passcode, You have " << lock-- << "Trys remaining" << endl;
if (lock == 0)
cout << " Too many tries mother. " << endl;
break;
}
cin >> response; //I can't seem to figure out what you wanted to do on this line, response isn't even declared, safe to delete.
return 0;
}
//passcode
#include <iostream>
usingnamespace std;
int main()
{
int passcode = 1234;
int input;
int tries = 3;
cout << "Enter passcode";
cin >> input;
//passcode loop
if (input == passcode)
cout << "Success!\n";
elseif (input != passcode) //You need a condition for your else if statement
{
while (input != passcode)
{
cout << "Sorry try again, you have " << tries-- << " left.\n";
cin >> input;
if (tries == 0 && input !=passcode)
{
cout << "Sorry you have exceeded the maximum attempts\n";
return 0;
}
elseif (tries == 0 && input == passcode) // this ensures that the program recognizes the correct input even on the last attempt otherwise I found that my program just ends if I don't add this.
{
cout << "Success!\n";
}
elseif (input == passcode) // I found that if I don't have this then the program does not work if you input the correct passcode on any attempts other than the first one.
{
cout << "Success!\n";
}
}
}
return 0;
}