What do you think about this code?
Jun 21, 2018 at 12:04pm UTC
So I've recently written a code in which you have to input your password and confirm it and program checks if both passwords are correct :) Tell me if I could have written anything better or in a shorter way :)
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 26 27 28 29 30 31 32 33
#include <iostream>
using namespace std;
bool status;
void checkIfpasswordsMatch(string password, string password_conf)
{
if (password==password_conf)
status = true ;
else
status = false ;
}
int main()
{
string password;
string password_conf;
cout << "Input your password: " ;
cin >> password;
cout << "Confirm your password: " ;
cin >> password_conf;
checkIfpasswordsMatch(password, password_conf);
if (status)
{
cout << endl;
cout << "Password Accepted." << endl;
}
else
{
cout << endl;
cout << "Password Denied!" << endl;
}
}
Jun 21, 2018 at 12:13pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
using namespace std;
int main()
{
string password;
string password_conf;
cout<<"ENTER YOUR PASSWORD" ;
cin>>password;
cout<<"CONFIRM YOUR PASSWORD" ;
cin>>password_conf;
if (password_conf==password)
cout<<"PASSWORD ACCEPTED" ;
else
cout<<"PASSWORD DENIED" ;
}
Last edited on Jun 21, 2018 at 5:47pm UTC
Jun 21, 2018 at 12:15pm UTC
Hi, there is pretty much always a way to make things better or shorter.
If you work with strings, remember to #include <string>, also you could eliminate the use of the bool status variable by doing this...
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 26 27 28 29 30 31 32 33 34 35 36
#include <iostream>
#include <string>
using namespace std;
bool checkIfpasswordsMatch(string password, string password_conf)
{
if (password == password_conf)
return true ;
else
return false ;
}
int main()
{
string password;
string password_conf;
cout << "Input your password: " ;
cin >> password;
cout << "Confirm your password: " ;
cin >> password_conf;
if (checkIfpasswordsMatch(password, password_conf))
{
cout << endl;
cout << "Password Accepted." << endl;
}
else
{
cout << endl;
cout << "Password Denied!" << endl;
}
return 0;
}
Also return 0 at the close of your program.
Last edited on Jun 21, 2018 at 12:20pm UTC
Jun 21, 2018 at 12:29pm UTC
Best way to pass strings is either as a reference or if possible as const reference.
Your checkIfpasswordsMatch could be as simple as:
1 2 3 4
bool checkIfpasswordsMatch(const string& password, const string& password_conf)
{
return password == password_conf;
}
Jun 21, 2018 at 1:10pm UTC
That is a sweet one liner Thomas...
Makes me think though that you could get rid of the function completely.
1 2 3 4 5 6 7 8 9 10 11
if (password == password_conf)
{
cout << endl;
cout << "Password Accepted." << endl;
}
else
{
cout << endl;
cout << "Password Denied!" << endl;
}
Jun 21, 2018 at 5:25pm UTC
You are right Manga,
there is no real need for a function to compare 2 strings.
Topic archived. No new replies allowed.