C++ Tutorial 6: Vectors, Files & Iterators // BONUS: User Authentication & Registration Database // Learn by doing

in #steemit8 years ago

header

The wait is over! You will finally have a full fledged authentication. And even better, A registration!

I hope you've enjoyed my steemit tutorials so far ^_^.

After this tutorial, you will know how to correctly create a user database for local authentication

Note: Databases should be encrypted with a private and public key etc. Since you see this on steemit you probably saw how much they're used.
As encryption in itself is complicated, You might not want to create your own custom encryption unless you are a math genious, then you will be safer with your own, unknown method of encryption.
I will talk about this more later, this tutorial we're going to focus on how to make a user database!

Tutorial contents:

  1. Vectors <- Very Important
  2. Iterators <- They will always be used with vectors
  3. Files <-Yes. Files. Data that you can actually store.
  4. BONUS! <- Full authentication program!

Vectors


Elfen-Lied-Vectors

Not that kind of vectors sadly, I would've conquered the world already if I could use them.

We're talking about Vectors

They can store about 1.073.741.823 elements.

Which makes them very useful :)

Let's get started!

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{           //Basic usage of vectors
    vector<string> myfirstvector;
    string input;
    cin >> input;
    myfirstvector.push_back(input);//Add element to the vector.
    cout << "You wrote: " << myfirstvector.size() << " Words, or elements\n";
    cout << "You wrote \"" << myfirstvector[0] <<"\"\n at position: " << 0 << endl;
    //Type another word so you understand how this works.
    cin >> input;
    myfirstvector.push_back(input); //Add another element.
    cout << "You wrote: " << myfirstvector.size() << " Words, or elements\n";
    cout << "You wrote \"" << myfirstvector[1] <<"\"\n at position: " << 1 << endl;
    system("pause"); 
}

Besides that, I always forget how to do it I look over it once and then I keep going.

This isn't rocket science... Not that rocket science impresses me all that much.

After all it's very easy to destroy something, Building something properly on the other hand...

Now that's impressive.

Some basic aspects of vectors:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{           //Basic usage of vectors
    vector<string> myvector;
    myvector.resize(5); //We can also resize it to 5 elements.
    //At this point, myvector contains "" "" "" "" "";
    myvector[0] = "Hello ";
    //At this point, myvector contains "hello " "" "" "" "";
    myvector[1] = "World!";
    //At this point, myvector contains "hello " "world!" "" "" "";
    myvector.resize(2); // now it contains:  "hello " "world!"
    myvector.resize(5, "x"); //This fills all empty spaces with "x"
    //At this point, myvector contains "hello " "world" "x" "x" "x";
    myvector.resize(2); //Back to "hello " "world" again, it erased all the "x"s.
    myvector.push_back(" Yay!");
    //And now a new element was added so it contains 3 elements
    //At this point myvector contains "hello" "world!" " yay!"
    //How you would print it all? well...
    for(int i = 0;i < myvector.size();i++)
    {
        cout << myvector[i];
    } 
    return 0;
}

And that's pretty much how vectors work. You can also do the same with ints, etc. The same rules apply.

And let's also finally find out how to read a line, not just a word, from the console :).

Getline:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    string str;
    getline(cin, str);//Gets the entire sentence you write, not just a word.
    system("cls");    //Or better to say gets line of input hence the getline();
    cout << "You entered this sentence: " << str << endl;//Now you can write entire sentences to a string
    system("pause");                                     //Not just a word.
}

Iterators


I find the following example to be the most useful example you will ever find about programming, as it already allows you to do a lot of things.

Hence the authentication I'm going to present later, either way, here's how they work.

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>//istream_iterator
#include <vector>
using namespace std;
int main()
{           //First, You must understand that istream stands for input stream.
            //And second, you must understand that ostream stands for output stream.
            //Now we're going to use iterators to split a "sentence" into "words"
    string sentence = "word1 word2 word3 word4"; //A sentence containing words
    stringstream ss(sentence); //We loaded the sentence into the stringstream
    //Iterators
    istream_iterator<string> begin(ss), end; //Begin: he string to iterate
                                    // End: serves as an ending for our iterator.
    //Vectors
    vector<string> words(begin, end); //push_back every element in the ss buffer
    for(int i = 0; i<words.size(); i++)
    {
        cout << words[i] << endl; //Print every word to the console followed by a newline.
    }
}

We finally have a proper way to split a line, into words.

Now you are going to have the knowledge to start understanding files later on.

img

Since we're going to make an authentication, it's time we show you how it works in detail so you don't get confused!

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>//istream_iterator
#include <vector>
using namespace std;
int main()
{
    string usersline = "Joe Amy Ben Don";//Every user to store in the line
    string passwline = "12345t6 password invalid iamdoncarlone";//Every password to store in the line.
    stringstream uss(usersline);//Users stream
    stringstream pss(passwline);//Paswords stream
    istream_iterator<string> ubegin(uss), uend;//Users iterators
    istream_iterator<string> pbegin(pss), pend;//Passwords iterators
    vector<string> users(ubegin, uend); //Where we store every user
    vector<string> passwords(pbegin, pend); //Where we store every password.
    for(int i=0; i<users.size() || i<passwords.size();i++)//Do this while we haven't parsed the entire database
    {
        cout << users[i] << " : " << passwords[i] << endl; 
    }
    
}

I know right it's awesome ^_^.

While I believe you should already have figured this out by yourself...

Here's how you would "Authenticate";

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>//istream_iterator
#include <vector>
using namespace std;
int auth(string u, string p)
{
    bool authstate = false;
    string usersline = "Joe Amy Ben Don";//Every user to store in the line
    string passwline = "12345t6 password invalid iamdoncarlone";//Every password to store in the line.
    stringstream uss(usersline);//Users stream
    stringstream pss(passwline);//Paswords stream
    istream_iterator<string> ubegin(uss), uend;//Users iterators
    istream_iterator<string> pbegin(pss), pend;//Passwords iterators
    vector<string> users(ubegin, uend); //Where we store every user
    vector<string> passwords(pbegin, pend); //Where we store every password.
    for(int i=0; i<users.size() || i<passwords.size();i++)//Do this while we haven't parsed the entire database
    {
        if(u == users[i] && p == passwords[i])
        {
            authstate = true;
            break;
        } 
    }
    return authstate;
}
int main()
{
    string u, p;
    cout << "Welcome to Auth - Alpha Edition!\n"
         << "Please enter your credentials.\n"
         << "Username: ";
    cin >> u;
    cout << "Password: ";
    cin >> p;
    if(auth(u, p)) // If the value is true, if you add ! in front of it it reverses roles
    {              // For Example, !auth(u, p) = false if it is true, and true if it is false!
        cout << "Success!\n";
    }
    else
    {
        cout << "Failure!\n";
    }
}

Awesome! Now we have a real method of authentication!

However, without working with files all of this is for nothing. It's time to finally learn how to play with files.

Working with files (fstream)


There's not a lot to talk about, it's similar to streams, it's just streaming files.

Therefor I will only give you examples with commented code.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Basic file operations
int main ()
{
  fstream myfile; //Input/Output Stream, We're writing & reading the file.
  myfile.open("info.txt"); //Your file can have any name and/or any extension you choose, it doesn't matter.
                           //In fact, we can use no extension at all (you can remove .db without reprecussions.)
  if(myfile.is_open())
  {
  myfile << "Hello info.txt!\n"; // Notice how similar it is to cout << "text";
  myfile.close();//Closing the file.
  cout << "File Input successful!\n";
  }
  else
  {
    cout << "Error, Could not open or create file.\n";
  }
  system("pause");
  //Alright, now open your file, with a txt editor(i.e. notepad) it should be in the same place as your main.exe
  //You should see "Hello info.txt!"
  //Attention! You will rewrite the file every time with this method.
  //In order to write to the end of a file for example you must specify that you want to OPEN the file not create if it doesnt exist etc.
  //You do that like this: myfile.open("info.txt", std::ios::app);
  //For more information document yourself with the programmers best friend:
  //GOOGLE! Search for <fstream>. You will find all of the info in a complete documentation on sites like cplusplus.com, or better.
  //Or just use this link provided in the title(click fstream)
  // #~~ Now let's read from a file. ~~#
  
  //First I'll ask you to manually write in the file "Hello Program!" without the quotes.
  //After this, press enter so the following code executes:
  myfile.open("info.txt");
  if(myfile.is_open())
  {
    string line;
    while(getline (myfile,line))//This is just so we read the file line by line
    {                           //Keep that in mind.
      cout << line << '\n'; //Print every line in the file.
    }                   
    myfile.close(); //Closing the file since we're done with it.
  }
  else
  {
    cout << "Error, could not open file!";
  }
  system("pause");
  return 0;
}

Congratulations, now you know how to work with files!

I will add the user authentication example in the comments very soon.

Please don't forget to upvote and follow if you liked my tutorial!

As always, the header image is of my own design
Everything i've written here is my own work.
List of images that are public domain:
Elfen-Lied-Vectors
*Note, memes are all public domain.

Coin Marketplace

STEEM 0.16
TRX 0.13
JST 0.027
BTC 57483.44
ETH 2574.21
USDT 1.00
SBD 2.48