So basically I have been trying to create a Login Database in C++, in which you must register first. So to do that I think I need to take the two string values, which are the "username" and the "password" that are entered by the user in my "register" function, and assign it in my "database" function as strings. I havent had any problems so far but I cant find a way how to compare these registered username and password with the inputs of my "login" function. Is there a way to create two paths inside one function and prevent functionA from going in way1 while functionB goes only in way2 ?
I am also open for new thoughts if my logic is wrong or too overcharging or too complicated etc.
It has been only a week since I started to learn C++ so please dont criticize too much =)
Well, if you're working with webpages and online stuff, then look up SQL. It's a large subject that I won't try and touch here.
If you are looking for something offline, then just save stuff to a file with ofstream. Then when you want to load the database, load it with ifstream.
This example code will populate your database. If you open the file it generates, you could add your own stuff manually too. Learn to append to files if you just want to add a single entry (maybe based on user input).
#include <string>
#include <fstream>
#include <iostream>
usingnamespace std;
constint SIZE = 100; // More than required is okay, less is BAD!
string Usernames[SIZE]; // From your database
string Password[SIZE]; // From your database
int GetNameIndex(string query, int size)
{
for (int i=0; i<size; i++) //We don't want to read garbage, so we limit our loop to the database size.
{
if (query == Usernames[i]) return i; //Return the index
}
return -1; //Error code
}
bool PasswordMatches(int index, string passwd)
{
return (passwd == Password[index]);
}
int main()
{
//Read the database;
ifstream fin("database.txt");
int i=0;
while (!fin.eof())
{
fin >> Usernames[i] >> Password[i];
i++; //This represents the number of lines we could extract from the database
}
//Now the rest of the program
string usrname, passwd;
cout << "Username:";
cin >> usrname;
int index = GetNameIndex(usrname, i); //Note that I now send the database size to this function.
cout << "Password:";
cin >> passwd;
if (!PasswordMatches(index, passwd))
{
cout << "Access denied";
return 0;
}
// Your program
return 0;
}