Well, assorted suggestions from coding standards I've worked to...
#1 declare variables as late as possible (at point of use)
#2 favor pre-increment
#3 use const where possible
#4 avoid abbrs, apart from well-known ones like "info".
#5 leave a space between operators
#6 use structs to group related variables (so you don't accidentally add a username (e.g. in alphabetical order) and accidentally offset all passwords...)
#7 minimize the use of globals, and make them stand out (e.g. g_ prefix) when you have to use them
#8 use spacer lines to make steps clear (a. get user name, b. get password, c. check values)
#9 use an unsigned type (size_t is typically unsigned int) to store an integer that should never be negative
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 37 38 39 40 41 42 43 44 45
|
<iostream>
<string>
<limits>
<cstdlib>
using namespace std;
// for some reason, I tend to skip the g_ for notFound...
static const size_t notFound = numeric_limits<size_t>::max();
struct UserInfo {
const char* username;
const char* password;
};
static const UserInfo g_aUserInfo[] = {
{"Mason", "1223"},
{"Amber", "8523"}
};
static const size_t g_userInfoCount = _countof(g_aUserInfo);
...
size_t login() {
string username;
cout << "Enter your user name : ";
cin >> username;
cout << endl;
string password;
cout << "Enter your password : ";
cin >> password;
cout << endl;
for( size_t index = 0; g_userInfoCount > index; ++index ) {
if( g_aUserInfo[index].username == username &&
g_aUserInfo[index].password == password ) {
cout << "Welcome " << username << endl;
return index;
}
}
cerr << "Login failed : invalid user name or password." << endl;
return notFound;
}
|