#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
int password=1234 ; //anything you want as the password
int password2 ;
cout<<"Input the password."<<endl;
cin>>password2;
if (password==password2)
{
//anything you want
}
}
2.Expand the password checking program and make it take multiple
usernames, each with their own password, and ensure that the right username is used for the right password. Provide the ability to prompt user's again if the first login attempt failed.
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
string userdef; // a string for storing input
string username1;
username1= "arda"; //anything you want as first username
string username2;
username2= "ahmet"; //anything you want as second username
cout<<"NOTE:The program is case secsitive."<<endl;
cout<<"Input the username."<<endl;
cin>>userdef;
//if input is username1
if (userdef==username1) //if input is username1
{
int password=1234 ;
int password2 ;
cout<<"Input the password."<<endl;
cin>>password2;
if (password==password2) //compare the password with first user's password
{
system("pause");
}
}
elseif (userdef==username2) //if input is username1
{
int password=9876 ; //compare the password with second user's password
int password2 ;
cout<<"Input password."<<endl;
cin>>password2;
if (password==password2)
{
system("pause");
}
}
else {cout<<"Wrong user name."<<endl;
system("pause");}
}
3.Write a password prompt that gives a user only a certain number of password entry attempts—so that the user cannot easily write a password cracker.
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
int a=2;
int password=1234 ;
int password2 ;
//Integer b counts how many times did you tried
//And integer a counts how many tries left to show
for (int b=0; b<3; ++b){
cout<<"input the password."<<endl;
cin>>password2;
if (password==password2){break;}
if (a==0){break;}
cout<<"Wrond input. "<<a<<" tries left.\n";
--a;
}
if (password==password2)
{
system("pause");
}
}
If you're using break inside a for loop, there's a decent chance it can be rewritten so that the actual condition the loop depends on to execute is in the loop condition. Sometimes a break may make more sense. Here, I would say it is out of place.
For instance, the following is equivalent to your number 3 code snippet (with the self destruct sequence added just for fun - it requires C++11.)