Page 1 of 2 12 LastLast
Results 1 to 10 of 13
  1. #1
    Senior Member
    Join Date
    Mar 2007
    Posts
    140

    C++ Tutorial For Beginners Lesson #2

    Hey Bryan again. Well in our first lesson we did a lot of step by step stuff slowly walking you into c++. I will step it up a bit in this tutorial and give you a chance to spread your wings a bit. I will explain some stuff that is not inside the code but a majority of the explanation will be inside the code.

    Now I would like you to go ahead and create a new folder to store your new project in. Otherwise you will end up overwriting your main.cpp from your first project.

    example:

    C:\DevCpp\Project1\Day1Project1.dev
    C:\DevCpp\Project2\Day2Project2.dev

    This is how I did mine it may work for you too.

    ---

    Okay now for the fun stuff. My code will be increasingly complex as we move forward through these lessons. So try to keep up if you fall behind chances are I explained it somewhere in the current or previous lesson so go back and read it so you can understand what is going on.

    In our first exercise we will be using a Structure to hold a string and the number of characters in that string. Furthermore we will be using two new functions strlen and strcopy both of which are explained moreover in the code. So here comes the code and the visual aid for the output.

    VA-01:
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    /*
     This is a struct or structure it basically allocates more than one
     type of memory to the same address location. This is very useful
     you may not see the point of it now but you will soon.
    */
    
    struct StringHelper
    {
     char *szBuffer;
     int nBufferCount;
    };
    
    
    int main(int argc, char *argv&#91;])
    {
      StringHelper shStructure;
      /*
       - Declare our stringhelper structure so we can use it.
       - our structure contains two inner variables szBuffer ;
       - and nBufferCount
      */
      
      char *szStringToCopy="Hello this is a string that we are going to add to our struct;";
      /*
        by the way the structure has no memory allocated to it&#39;s szBuffer
        so we will have to allocate some
        - First we will take the length of szStringToCopy so we make sure
         that we have enough memory so we don&#39;t get an error.
        - We will do that with strlen. All this does is take the number of
         characters in an array of characters or also called a string.
      */
      
      size_t sztSizeOfString = strlen(szStringToCopy);
      printf("Our string is %d characters long\n",sztSizeOfString);
      
      /*
       Now we need to allocate that number of elements to szBuffer inside
       our structure so we don&#39;t get a memory under-run.
      */
      
      shStructure.szBuffer = new char[sztSizeOfString];
      
      /*
       Now that szBuffer has X number of elements loaded to it we need to
       copy our string to it. So we will use the function strcpy(). This
       is a string copying function used for null-terminated strings. 
       
       - the basic setup for strcpy is strcpy(destination,source);
      */
      
      strcpy(shStructure.szBuffer,szStringToCopy);
      
      /*
       Now szBuffer that is inside our shStructure (StringHelper structure)
       lets set nBufferCount inside that structure to the number of charaters
       in the string. This way we will not have to use strlen() again.
      */
      
      shStructure.nBufferCount = (int) sztSizeOfString;
      
      /*
       Notice now that I have used (int) this will convert sztSizeOfString from
       type &#39;size_t&#39; to type &#39;int&#39; so we will not get a warning or an error
       
       - Lets print this string out that is now inside our structure;
      */
      
      
       printf("This is our string: %s\n", shStructure.szBuffer);
       printf("This is the length: %d\n", shStructure.nBufferCount);
      
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    VA-02:


    Fun Right?! Yeah I think so too so lets get into some functions. We will start by making some very basic functions for you to use. Your own functions that will manipulate strings in various ways. Fun Fun Fun!

    So start by deleting everything you personally typed in like you did in lesson #1. In this next exercise we will write a "right" function you may know it from mIRC as $right() our right function will only support positive numbers so far but we will add negative support next. Right now go ahead and copy down this code and read it thoroughly.

    VA-03:
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    /*
    type &#39;void&#39; is basically the jack of all trades of types. It does not require
    a return value and it is also very simple, fast, and a useful type to use.
    */
    void szRight(char *szDestination, char *szSource, int nCount)
    {
       /*
        Firstly we must know what our function will do typically
        I understand Right as being a function that will take X
        number of characters from the right and return them asin
        mIRC for those fans out there.
        
        - example: right(test,3) = est
        - sounds good right? :-)
        - later we will use negatives and ellaborate on this
         function some more.
         
        we will need the length of the string so we can formulate where to start.
        
        -example: test = 4 characters if we want three of those then
         4 - 3 = 1 we need to start at position 1 which will be &#39;e&#39;
         since C++ counts from 0 and up.
         so 0 = &#39;t&#39;, 1 = &#39;e&#39;, 2 = &#39;s&#39;, 3 = &#39;t&#39;
       */
       
       size_t sztSizeOfSource = strlen(szSource);
       
       int nSrcPosition = (int)sztSizeOfSource - nCount, // 4 - 3 = 1 remember?
         nDestPosition = 0; // we need to keep track of where we&#39;re putting these characters
       
       for (; szSource[nSrcPosition] /* while szSource does not equal null */; nSrcPosition++, nDestPosition++)
       {
         szDestination[nDestPosition] = szSource[nSrcPosition]; // copy char from source to desitination
       }
       
       /*
        The for loop broke after it hit the null terminator so we will have to add it manually.
        To do this we will just say szDestination[nDestPosition] = 0; or &#39;\0&#39;; whatever makes you happy.
       */
       
       szDestination[nDestPosition] = 0; 
    }
    
    int main(int argc, char *argv&#91;])
    {
      char szDestinationString[21]; // allocate enough memory for our szRight();
      char szSourceString&#91;] = "Hello all you chaps that came to my show. I hope you enjoy it!";
      
      printf("This is our original string: %s\n", szSourceString);
      // We need to perform our szRight(destination,source,count);
      szRight(szDestinationString,szSourceString,20);
      printf("This is our string after the szRight: %s\n", szDestinationString);
    
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    VA-04:


    Alright then this is fun right.. Now we will add the availability of negative numbers to this. How we will do it is make a function that is able to convert a negative number to a positive. I have done this and then we will start at that position in the string and copy forward from there.
    Have a look as you copy this down.

    VA-05:
    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    /*
    this function is used to make a negative number
    the positive inversion of that number.
    */
    
    int nPositive(int nNegativeNumber)
    {
      /*
       -1 - -1 = 0
       0 - -1 = +1
      */
      return (nNegativeNumber-nNegativeNumber-nNegativeNumber);
    }
    
    void szRight(char *szDestination, char *szSource, int nCount)
    {
    
      if (nCount >= 0) // if nCount is greater than or equal to zero
      {
       size_t sztSizeOfSource = strlen(szSource);
       
       int nSrcPosition = (int)sztSizeOfSource - nCount,
         nDestPosition = 0;
       
       for (; szSource[nSrcPosition]; nSrcPosition++, nDestPosition++)
       {
         szDestination[nDestPosition] = szSource[nSrcPosition];
       }
    
       szDestination[nDestPosition] = 0;
      }
      else
      {
        /*
         Using a negative number you will get a result like this:
         szRight("test",-1); = "est" 
         szRight("test",-2); = "st"
         It converts -2 to 2 and then starts at the second element
         0 = &#39;t&#39;, 1 = &#39;e&#39;, 2 = &#39;s&#39;, 3 = &#39;t&#39;
        */
        if (nPositive(nCount) < strlen(szSource)) /*
        if ( (+)nCount is less than the length of source then continue )
        */
        {
         int nDestPosition = 0,
           nSrcPosition = nPositive(nCount);
         for(; szSource[nSrcPosition]; nSrcPosition++, nDestPosition++)
         {
          szDestination[nDestPosition] = szSource[nSrcPosition];
         }
         szDestination[nDestPosition] = 0;
        }
        else/*
        else then copy source to dest and return
        */
        {
          strcpy(szDestination,szSource);
        }
      }
    }
    
    int main(int argc, char *argv&#91;])
    {
      /* Well we will always have to have enough memory allocated inside
        szDestinationString so that the szRight will not cause an error
        so lets think about this we can allocate the same ammount of
        memory as the source and always have enough and never go over
        but we will be wasting memory, which in this situation it is
        win some lose some but it is better to waste a little than to
        have an error. So we will move destination&#39;s declaration beyond
        that of source so we can use strlen(source) to help allocate dest.
      */
      char szSourceString&#91;] = "Hello all you chaps that came to my show. I hope you enjoy it!";
      char *szDestinationString;
      
      szDestinationString = new char [strlen(szSourceString)];
      if (!szDestinationString) /*
      if szDestinationString is null then the memory alloc failed in the
      situation of a failure with the &#39;new&#39; operator it will set the dest
      to null or throw an exception which we will work with later but not now.
      For now we will only work with the null.
      */
      {
        printf("Failed to allocate memory!\n");
        system("PAUSE");
        return EXIT_FAILURE;
      } 
      printf("This is our original string: %s\n", szSourceString);
      // We need to perform our szRight(destination,source,count);
      szRight(szDestinationString,szSourceString,-20);
      printf("This is our string after the szRight: %s\n", szDestinationString);
    
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    Here is the resulting visual aid

    VA-06:


    Now as we move along into our fourth exercise I will tell you what I will be doing in this one. In the 4th I will be making a gettok function in which for those of you not familiar with mIRC. Gettok basically Gets a Token from a string.

    example:
    gettok("hello I&#39;m from Amsterdam!",2," ")

    " " = space so with every space count up one number (starting at 1)



    HelloI&#39;mfromAmsterdam!


    1234



    now as you may have guessed 2 means the second token which is "I&#39;m" in this case.

    Nice huh? Indeed it is and luckily C++ has a useful function that will help with our work. This function is called strtok() you will see it in action in this code to come. Now go ahead and delete what you&#39;ve written in so far and begin typing this out.

    VA-07:

    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    void szGettok(char *szDestination, char *szSource, int nToken, char *szDelimiters)
    {
       char *szDestinationBuffer;
       szDestinationBuffer = strtok(szSource,szDelimiters);// initiate the tokenize with
       // the source and the list of delimiters
       
       for(int nCurrentToken=1; nCurrentToken <= nToken && szDestination != NULL; nCurrentToken++)/*
       (curtoken less than or equal to token and dest does not equal null)
       */
       {
        if (nCurrentToken == nToken)
        {
          strcpy(szDestination,szDestinationBuffer); // now copy the token we have selected!
          break; // break simply stops the loop where it is and exits
        }
        szDestinationBuffer = strtok(NULL,szDelimiters); //place next token inside szDestination
       }
    }
    
    int main(int argc, char *argv&#91;])
    {
      char szSourceString&#91;] = "I was walking, yesterday;hey what do you say?";
      char *szDestinationString;
      
      try // will try to perform the task inside this statement
      {
       szDestinationString = new char[strlen(szSourceString)];
      } catch(...) // if it fails and an error is thrown this will &#39;catch&#39; it.
      // and you can process that error code if you like..
      {
       printf("An error occurred during the allocation\n");
       system("PAUSE");
       return EXIT_FAILURE;
      }
      
      szGettok(szDestinationString,szSourceString,4," ,;");
      
      printf("this is the token: %s\n",szDestinationString);
      
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    Now this is the output that you should receive.

    VA-08:


    Alright, well I&#39;m sure you&#39;re familiar with all of that now. Lets continue on to making a class. A class is basically a group of functions and variables that are available to you at any time you wish to use them. That&#39;s a simple way of putting it. What we will do in our class is make a stack.

    For example when you push something onto a stack it grows higher. When you pop something from a stack it gets smaller. I&#39;ll give you an example:

    [___] <- top of stack (we call it the top because it is the beginning of the stack)

    when we push something onto the stack it works like this

    [___] <- newest in the stack
    [___] <- top of stack

    if we were to pop from the stack it would remove the newest entry to the stack for example if we popped now it would remove the second one.

    [___] <- waiting to be popped
    [___] <- top of stack

    << After pop >>

    old position is free now the newest entry was popped.

    [___] <- top of stack

    You can think of it as a stack of papers numbers 1-100. 100 being the top if you add to the stack of papers it grows but if you take one off it shrinks. We will use this again in the future when I show you how to make your first linked-list. That&#39;s not necessary right now.

    So go ahead and take this time to delete your previous code and starting typing this out.

    VA-09:

    Code:
    #include <cstdlib>
    #include <iostream>
    
    #define MAX_ARRAY 8
    
    // this defines a variable that is globally useable throughout this document
    
    using namespace std;
    class stack
    {
       int stack_array[MAX_ARRAY];
       int stack_top;
      public:
       stack(void); // is the initializer of the stack class
       ~stack(void); // is the destroyer of the stack class
       void push(int nAddToStack); // adds an entry to the stack
       int pop(void); // removes the newest entry from the stack
    };
    
    stack::stack(void)
    {
     stack_top = 0; // set the stack count to zero because the stack is empty
     printf("Stack initialized\n");
    }
    stack::~stack(void)
    {
     printf("Stack destroyed\n");
    }
    void stack::push(int nAddToStack)
    {
     if (nAddToStack == MAX_ARRAY)
     {
       printf("The stack is at maximum compacity!\n");
       return;
     }
     stack_array[stack_top] = nAddToStack; // insert new integer into stack array
     stack_top++; // increase stack count by 1
    }
    int stack::pop(void)
    {
       if (stack_top == 0)
       {
        printf("The stack is now empty!\n");
        return 0; 
       }
       stack_top--; // decrease stack count by one
       return stack_array[stack_top]; // return the integer being removed from stack
    }
    
    int main(int argc, char *argv&#91;])
    {
      stack stkObject; // declare instance of our class
      
      for(int nIncrement = 1; nIncrement < 8; nIncrement++)
      {
        stkObject.push(nIncrement); // access push function from the class
        printf("Adding %d to the stack\n",nIncrement);
      }
      
      stkObject.push(8); // push last object into stack
      
      for(int nIncrement = 7; nIncrement; nIncrement--)
      {
        printf("Removing %d from the stack\n",stkObject.pop()); // use pop function from class
      }
      
      stkObject.pop(); // pop last object from stack
      
      delete &stkObject; // destroy stack class
      // & is used to return the address of stkObject.
      
      system("PAUSE");
      return EXIT_SUCCESS;
    }
    And here is the last visual aid you will get in this tutorial.

    VA-10:



    ---

    That wraps it up for the beginner tutorial lessons. I will start on some intermediate tutorials some other time when I am bored. Good Luck with the coding fellers.


  2. #2

    Re: C++ Tutorial For Beginners Lesson #2

    Cool stuff kozical, keep up the awesome tuts


  3. #3
    Site Admin xHalt's Avatar
    Join Date
    May 2006
    Location
    Belgium
    Posts
    7,917

    Re: C++ Tutorial For Beginners Lesson #2

    Quote Originally Posted by null
    Cool stuff kozical, keep up the awesome tuts
    Thank you! Come again! 8)
    Btw: I hereby claim the right to bundle these and publish them...

  4. #4
    Senior Member
    Join Date
    Mar 2007
    Posts
    140

    Re: C++ Tutorial For Beginners Lesson #2

    Jahaha!

  5. #5

    Re: C++ Tutorial For Beginners Lesson #2

    Heh, some sort of CU learn-to-code page (or wiki? hmmm..) would seem in order if people keep posting cool stuff like this


  6. #6
    Senior Member
    Join Date
    Mar 2007
    Posts
    140

    Re: C++ Tutorial For Beginners Lesson #2

    I agree null. I&#39;m in the process of another an intermediate tutorial. However I&#39;m behind in my school work now so I may not get it out tomorrow I am not sure. I hopefully will find time though.

  7. #7

    Re: C++ Tutorial For Beginners Lesson #2

    Wunderbar!
    I never found any good tut&#39;s untill you came up with these.
    Nice man, really thanks again ;D.
    Google is your friend
    Before asking any (stupid) questions use the search-option first
    Stupid question = stupid answer
    I do NOT respond to private messages when you ask for hacks.

  8. #8

    Re: C++ Tutorial For Beginners Lesson #2

    I might help write some stuff, I have a good idea for tuts


  9. #9
    Junior Member
    Join Date
    May 2007
    Posts
    8

    Re: C++ Tutorial For Beginners Lesson #2

    Lol i hate leaning but this is just so interesting

    Keep on this things

    Gr Fulltime

  10. #10
    Semi-Coder
    Join Date
    Jun 2007
    Posts
    1,003

    Re: C++ Tutorial For Beginners Lesson #2

    Very nice job.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 4
    Last Post: June 16th, 2011, 21:33
  2. C++ Tutorial For Beginners Lesson #1
    By Kozical in forum Basics
    Replies: 31
    Last Post: September 28th, 2009, 23:27
  3. [Help]I'm looking for tutorial...
    By SyncX in forum Basics
    Replies: 3
    Last Post: March 13th, 2009, 03:15
  4. Replies: 5
    Last Post: January 11th, 2008, 00:27
  5. [Tutorial] Basic Twirl Effect tutorial
    By JohnnyD in forum Tutorials (Art)
    Replies: 4
    Last Post: September 27th, 2007, 02:23

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •