A Digital Age Deserves A Digital Leader

C++ Source Code Please

C++ Source Code Please

Postby Omex » Sun Feb 22, 2004 6:34 pm

Can anyone send me a source code file that I can look at to see how an actual windows based program works? I'm trying to learn C++ with a few books but they have these stupid little "Hello World!" things and that's getting me nowhere fast.

Please help, thanks guys.


Omex
To deny our own impulses is to deny the very thing that makes us human.
PRO Level 2
User avatar
Posts: 45
Joined: Wed Feb 18, 2004 7:08 pm

Postby Injunfarian » Sun Feb 22, 2004 7:07 pm

http://www.planetsourcecode.com
basic code there i started off with that site for alot of languages learn by example works good.
<a href="http://www.secretsofwar.net/index.asp?referer=injunfarian" target=_blank>Good Webbased Game</a>

<a href="http://selectaz.com" target=_blank><img src="http://selectaz.com/popup/stats.php" border=0></a>
PRO Level 3
User avatar
Posts: 63
Joined: Sat Jan 18, 2003 8:15 pm

Postby Weaver » Sun Feb 22, 2004 8:57 pm

Pretty much all console C++ programs that use the standard library behave the same way. You want some source, I can provide you with some real stuff, real big boy stuff. :)

I don't want to sound condescending or rude, but this may be a little bit advanced for you right now, but it will definitely show you some syntax and advanced features of C++.

Warning, this post is going to get long since I will post 3 source files. The first two are a template class implementation of a "queue" using a "linked list" under the hood. The first one is the .h (header file, class declaration) that defines the class. The second one will be the .cpp (source file, class implementation/definition).

It is important to note that these two files are really useless in terms of actually "doing something." You need another implementation, sometimes called "client code" that actually makes the class do work. This will be the third file. It simulates a line (queue) that you would find at a checkout counter.

Note: Ignore some of the weird comment headings on these files. This was an assignment in my C++ data structures class. The weird headers were pre-written, they didn't want us to change them. I assure you that nearly all the code in this is my own (about 95%).

Here is the first source file (queuelnk.h). This defines the class, it also defines the class as a template class.

Code: Select all
//--------------------------------------------------------------------
//
//  Laboratory 6                                          queuelnk.h
//
//  Class declarations for the linked list implementation of the
//  Queue ADT
//
//--------------------------------------------------------------------

#ifndef QUEUELNK_H   //Macro guard
#define QUEUELNK_H

#include <iostream>
#include <stdexcept>
#include <new>

template < class DT >        // Forward declaration of the Stack class
class Queue;

template < class DT >
class QueueNode              // Facilitator class for the Queue class
{
  private:

    // Constructor
    QueueNode ( const DT &nodeData, QueueNode *nextPtr = NULL );

    // Data members
    DT dataItem;         // Queue data item
    QueueNode *next;     // Pointer to the next element

  friend class Queue<DT>;
};

//--------------------------------------------------------------------

template < class DT >
class Queue
{
  public:

    // Constructor
    Queue ( int ignored = 0 );

    // Destructor
    ~Queue ();

    // Queue manipulation operations
    // Enqueue data element
    void enqueue ( const DT & newData ) throw ( std::logic_error );

    // Dequeue data element
    DT dequeue () throw ( std::logic_error );

    void clear ();                            // Clear queue

    // Queue status operations
    bool isEmpty () const;                    // Queue is empty
    bool isFull () const;                     // Queue is full
    bool isEmpty () const;                    // Queue is empty
    bool isFull () const;                     // Queue is full

    // Output the queue structure -- used in testing/debugging
    void showStructure () const;

  private:

    // Data members
    QueueNode<DT> *front,   // Pointer to the front node
                  *rear;    // Pointer to the rear node

   std::size_t numItems;   //John's added functionality, num items in queue
};

#include "queuelnk.cpp" //Template classes Queue + QueueNode Implementation

#endif   //End macro guard


Here is the second source file (queuelnk.cpp). This actually defines what the class does. You will also note that queuelnk.h #include's queuelnk.cpp at the end of the class declarations. This is because it is a template class, and always needs the definition available.

Code: Select all
/*************************************************************************
Filename: queuelnk.cpp
Author: John Urbanek
Date: 11.24.03

Terminal Info:
   Tabstop: 3 char
   Termwidth: 80 char @ tabstop 3

If your terminal differs, don't complain.

*************************************************************************/

//QueueNode class definitions

   //Constructor
template <class DT>
QueueNode<DT>::QueueNode<DT>( const DT &nodeData,
                              QueueNode<DT> *nextPtr = NULL)
{
   dataItem = nodeData;
   next = nextPtr;
}


//Queue class definitions

   //Constructor
template <class DT>
Queue<DT>::Queue<DT>( int ignored = 0 )
{
   //Since there isn't a maximum size to a queue
   //implemented with our linked list, we don't have to
   //setup a maxSize member or anything like that.

   //We can just initialize the front and rear to NULL
   //and numItems to 0

   front = rear = NULL;
   numItems = 0;
}

   //Destructor
template <class DT>
Queue<DT>::~Queue<DT>()
{
   if( isEmpty() ) return;

   QueueNode<DT>* next = front->next;
   for(QueueNode<DT>* cur = front; cur && cur != rear; front = next)
   {
      next = front->next;
      delete cur;
      cur = NULL;
   }
}

//Queue Manipulation Operations

"queuelnk.cpp" 175L, 3338C

   QueueNode<DT>* next = front->next;
   for(QueueNode<DT>* cur = front; cur && cur != rear; front = next)
   {
      next = front->next;
      delete cur;
      cur = NULL;
   }

   front = rear = NULL;
   numItems = 0;
}

//Queue status operations

   //Queue is empty
template <class DT>
bool Queue<DT>::isEmpty() const
{
   //If front == NULL then the queue has to be empty.
   return front ? false : true;
}

   //Queue is full
template <class DT>
bool Queue<DT>::isFull() const
{
   //Queue can never be full, so always return false.
   return false;
}

//Output the queue structure -- used in testing/debugging

template <class DT>
void Queue<DT>::showStructure() const
{
   if( isEmpty() )
   {
      std::cout << "\n\t.::QUEUE EMPTY::." << endl;
      return;
   }

   QueueNode<DT>* cur = front;
   std::size_t pos = 1;

   while(cur)
   {
      std::cout << "Position " << pos << " -->  " << cur->dataItem << "\n" << endl;

      cur = cur->next;
      pos++;
   }

   std::cout << "\n\t.::QUEUE CONTAINS " << numItems << " ENTITIES::." << endl;

}

   QueueNode<DT>* next = front->next;
   for(QueueNode<DT>* cur = front; cur && cur != rear; front = next)
   {
      next = front->next;
      delete cur;
      cur = NULL;
   }

   front = rear = NULL;
   numItems = 0;
}

//Queue status operations

   //Queue is empty
template <class DT>
bool Queue<DT>::isEmpty() const
{
   //If front == NULL then the queue has to be empty.
   return front ? false : true;
}

   //Queue is full
template <class DT>
bool Queue<DT>::isFull() const
{
   //Queue can never be full, so always return false.
   return false;
}

//Output the queue structure -- used in testing/debugging

template <class DT>
void Queue<DT>::showStructure() const
{
   if( isEmpty() )
   {
      std::cout << "\n\t.::QUEUE EMPTY::." << endl;
      return;
   }

   QueueNode<DT>* cur = front;
   std::size_t pos = 1;

   while(cur)
   {
      std::cout << "Position " << pos << " -->  " << cur->dataItem << "\n" << endl;

      cur = cur->next;
      pos++;
   }

   std::cout << "\n\t.::QUEUE CONTAINS " << numItems << " ENTITIES::." << endl;

}


The last source file (storesim.cpp) is what is referred to as client code, it will put the above class to work and do something. Note it has a main().

Code: Select all
//--------------------------------------------------------------------
//
//  Laboratory 6, In-lab Exercise 1 shell               storesim.cpp
//
//  Store simulation program
//
//--------------------------------------------------------------------

// Simulates the flow of customers through a line in a store.

#include <iostream>
#include <iomanip>
#include <cstdlib>   //for rand() and srand()
#include <ctime>     //for time()
#include "queuelnk.h"



void main ()
{
    Queue<int> custQ;      // Line (queue) of customers containing the
                           //   time that each customer arrived and
                           //   joined the line
    int simLength,         // Length of simulation (minutes)
        minute,            // Current minute
        timeArrived,       // Time dequeued customer arrived
        waitTime,          // How long dequeued customer waited
        totalServed = 0,   // Total customers served
        totalWait   = 0,   // Total waiting time
        maxWait     = 0,   // Longest wait
        numArrivals = 0,   // Number of new arrivals
        maxRand     = 3;

    cout << endl
         << "Enter the length of time to run the simulator : ";
    cin >> simLength;

    srand( int( time(NULL) ) );  //Set the seed

    for ( minute = 0 ; minute < simLength ; minute++ )
    {
        // Dequeue the first customer in line (if any). Increment
        // totalServed, add the time that this customer waited to
        // totalWait, and update maxWait if this customer waited
        // longer than any previous customer.

         if( !custQ.isEmpty() )
         {
            totalWait += waitTime = minute - custQ.dequeue();  //Calc. time in line
            totalServed++; //Increment totalServed

            if( waitTime > maxWait ) maxWait = waitTime; //If new max, set it.
         }

        // Determine the number of new customers and add them to
        // the line.

         //Came up with the Random range thing on my own thank you... :)  Took me long enough.

         switch( int( float(rand()) / float(RAND_MAX) * (maxRand + 1) ) )  // "() city" I know :)
         {
            case 0:
            case 3:
               break;

            case 1:
               custQ.enqueue(minute);
               break;

            case 2:
               custQ.enqueue(minute);
               custQ.enqueue(minute);  //A for loop is just too much for only 2 ... :)
               break;

            default: //There should never be a default, but just in case random messes up...
               break;
         }
    } //End for

    cout << endl;
    cout << "Customers served : " << totalServed << endl;
    cout << "Average wait     : " << setprecision(2)
         << double(totalWait)/totalServed << endl;
    cout << "Longest wait     : " << maxWait << endl;


There you have it. Some real life C++ code. Note that these sources were all compiled on Linux (2.4.18) using gcc 2.95.3. They should compile on most other compilers.

If you wanted something a little bit simpler, sorry. Just let me know what kind of something you are looking for. I know this one is probably a little bit over the top, all I could find in my "archive" on short notice.

BTW, I don't like linking to offsite source code repositories for example like Injun did. I find it much more useful to post real code that I have written and can explain if you have questions.

-Weaver

Edit: Extraneous line in source, removed.
Public Keys

The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of pi change.
-- FORTRAN manual for Xerox Computers
PROfessional Member
User avatar
Posts: 1967
Joined: Wed Jun 19, 2002 12:05 am
Location: /home/weaver/

Postby Weaver » Tue Feb 24, 2004 2:05 am

I apologize for dismissing your offsite submission so quickly Injun. The site you recommended is actually filled with great examples and some useful code.

I apologize.

-Weaver
Public Keys

The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of pi change.
-- FORTRAN manual for Xerox Computers
PROfessional Member
User avatar
Posts: 1967
Joined: Wed Jun 19, 2002 12:05 am
Location: /home/weaver/

Return to HTML, CSS, and Scripts

Who is online

Users browsing this forum: No registered users and 0 guests

cron
cron