Archive for ‘C++’

May 8th, 2010

C++ Standard Template Library (STL) vector class example

This C++ program illustrates how to use the Standard Template Library (STL) vector class


#include < vector >
#include < iostream >
using namespace std;

int main()
{
    // vector is a template, the <int> means it is a vector of ints
    vector<int> numbers;  

    // push_back() puts a new value at the end (or back) of the vector
    for (int i = 0; i < 10; i++)
        numbers.push_back(i);

    cout << "print all elements in vector" << endl;

    // This is one way to iterate through a vector and print all the values
    for (int i = 0; i < numbers.size(); i++)
        cout << numbers[i] << endl;

    // This is the preferred way to iterate through a vector

    // an iterator is a special object used to keep track of internal structures
    vector<int>::iterator iter;
    for (iter = numbers.begin(); iter != numbers.end(); iter++)
        cout << *iter << endl;

    cout << "now print it backwards" << endl;
    iter = numbers.end();
    for (iter--; iter != numbers.begin(); iter--)
        cout << *iter << endl;
    cout << *iter << endl;
}

// In order to motivate why the iterator mechanism show above is more
// efficient that using the index method (the numbers[i] method)
// consider how you would implement finding a specific element of a
// linked list.  Each time this function is called it has to start
// at the head of the list.

/*
bool List::index(int i, int &value)
{
    Node *ptr;
    for (ptr = m_head; i > 0; ptr = ptr->m_next, i--)
        ;
    if (ptr != NULL)
    {
        value = ptr->m_value;
        return true;
    }
    else return false;
}
*/

Tags:
May 8th, 2010

C++ wait for key press to continue execution example

Simple C++ program that waits for a key to be pressed to continue execution of the program.


#include " stdafx.h "
#include < iostream >

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  cout << "Press 'n' and then ENTER to continue!" << endl;
  while (1)
  {
    if ('n' == getchar())
       break;
  }
}

Tags:
May 8th, 2010

C++ Using the standard template library (STL) map example

This program demonstrates using the standard template library (STL) map it reads pairs of data and inserts them into a map then it reads names and looks those names up in the map
A map stores a collection of pairs For example, consider this collection of data: Tom is 42 years old Sally is 20 years old Fred is 21 years old We can think of this data as three “pairs” A map stores these pairs. For each key (a name in the above example) there is a single value


#include < map >
#include < string >
#include < iostream >
using namespace std;

int main()
{
    // maps are parameterized by two types.  The first is the type of the key,
    // the second is the type of the thing being stored in the map
    map<string, string> my_map;
    string owner_name;
    string pet_name;

    cout << "enter owner names and pet name pairs: " << endl;
    while (cin >> owner_name)
    {
        if (owner_name == "quit")
            break;
        cin >> pet_name;
        // insert the pet_name into the map using the owner_name as the key
        my_map[owner_name] = pet_name;
    }

    cout << "enter owner names to lookup:" << endl;
    while (cin >> owner_name)
    {
        if (owner_name == "quit")
            break;
        // NOTE: this code is not very good.  
        // If an owner_name is not in the map, this code prints an
        // empty string.
        cout << owner_name
             << "'s pet is <"
             << my_map[owner_name]
             << ">"
             << endl;
    }
}

Tags:
May 8th, 2010

c++ Sample program to test compilation

Here is a simple C++ program to test compilation:

// Sample program to test compilation
#include <iostream>
using namespace std;

int main()
{
    cout << "Hello world." << endl;
}

December 20th, 2009

How To Compile C And C++ Programs With Linux

1. Editing source files

a) Use either the emacs/xemacs editor or vi editor (can be difficult to use) or pico (easy to use). If you use emacs editor, you can compile and run your program from within this fancy editor.

b) Save the source file with a .cpp extension or .h extension if you are creating a header file.

2. Compiling and linking programs (done in one step)

a) For one source file, enter at the prompt

g++ filename

This will produce an executable with filename a.out

b) For multiple source files, enter g++ filename1 filename2 filename_etc.

c) To explicitly link in a library such as the math library, enter g++ filename -lm.

d) Executable file will automatically be called a.out unless you use the option -o output.

g++ -o output_filename input_filename

3. Running the program

a)  Enter a.out (or the output filename if you used the -o option)

4. For debugging, you should compile your source code with the –g option. gdb –help will list help for the debugger. You can then use the following command for debugging.

gdb output_filename

December 20th, 2009

How To Compile C And C++ Programs with Microsoft Visual C++ 6.0

1)      Start the Microsoft Visual C++ 6.0,  which is under Microsoft Visual C++ Developer Studio Meuu.

2)      Select File | New and click the Projects tab.  Click on Win32 Console Application and in the Location textbox position to the directory in which you want to create the project (Recommended directory is the directory of your intranet account).  In the Project Name textbox type the name of the project, e.g. proj1 and set the radio button to “create new workspace.”  Accept all other default settings.  You do not need to add the extension .dsw to the project name (Visual C++ will do it).  Click OK.  In the window that follows, set the radio button to “An empty project.”  Click the Finish button and then the OK button.  You will create a proj1 subdirectory as well as the proj1.dsw project workspace file within the subdirectory.

3)      To create source code files and insert them into the project, select File | New, click the Files tab and select the file type.  Specify a file name, a directory location (should be the same directory as the one in which you created your project) and the project to which you want to add the file.  Click OK to create a new file of the chosen type.  Type in your source code and save it, e.g. save it as Hello.cpp in the proj1 directory.

4)      If you need to add files to the project at a later date, select Project | Add to Project | New and click on the Files tab.  You will see a window similar to the window from the step above.

5)      To compile your project, click on Build | Build proj1.exe.  Correct any compiler errors and if necessary, build the project again.

6)      To run your program, select Build | Execute proj1.exe.

7)      To run the debugger, select Build | Start Debug.

a)      The submenu option Go executes the program from start to finish.

b)      To use the  debug options, select the submenu option Step Into.  You will now see a main menu option called Debug.

i) F11 steps into functions.

ii) F10 steps over functions.

iii) Shift + F11 steps out.

c)      The output screen can be seen by selecting the window from the screen bottom list of open windows.

d)      You can also set up breakpoints (via the Edit menu or the hand icon or F9) and view the contents of variables.

e)      Use the Debug | QuickWatch option to inspect the contents of variables.  You can also see auto and local variables and “this” in the lower panels of your screen.

8)      To close the project, click File | Close Workspace.  After a project has been built, you can open it by selecting File | Open Workspace and selecting the .dsw file (the project workspace file) in the directory in which the project was originally created.

December 19th, 2009

Best Coding And Debugging Guide

* Write small simple programs to test constructs you haven’t used before or about which you feel shaky. It’s easier to locate your misunderstanding in a short program than in a long one.

* When you’re debugging a program, pay attention only to the first error. The others may simply be side-effects of that first error.

* When you’re writing a program, keep the specification in front of you. How else can you be sure that you’re solving the correct problem?

* Don’t attempt to write out all the code at once and then try to debug it.

* Always build on existing code which compiles and runs.

* Grow programs incrementally. If you extend a working program and it doesn’t work anymore, then you can localize the error.

* Keep working checkpoint programs as you move along. If you seriously wound your code, you can retreat to a prior version which worked.

* Implement a large program in well-defined steps. Examine the problem and determine how you can implement the required capabilities in an incremental manner.

* Learn how to document errors:

· they must be repeatable;

· the code should be short;

· collect hardcopy of the program, the compile, and the test run.

* Human memory is fallible, and computers are unforgiving, so no one will believe you if you don’t have documentation. Experts can’t help you if you come in with a folktale — “I tried that, but it gave me an error.” You must be able to replicate the error.

* If you encounter an error that you can’t understand, then keep the code which generated the error and find out what was wrong. You may produce a working program by trying another approach, but if you don’t know why you got the error, then there’s a gap in your knowledge.

Write small simple programs to test constructs you haven’t used before or about which
you feel shaky. It’s easier to locate your misunderstanding in a short program than in a
long one.
When you’re debugging a program, pay attention only to the first error. The others may
simply be side-effects of that first error.
When you’re writing a program, keep the specification in front of you. How else can you
be sure that you’re solving the correct problem?
Don’t attempt to write out all the code at once and then try to debug it.
Always build on existing code which compiles and runs.
Grow programs incrementally. If you extend a working program and it doesn’t work
anymore, then you can localize the error.
Keep working checkpoint programs as you move along. If you seriously wound your
code, you can retreat to a prior version which worked.
Implement a large program in well-defined steps. Examine the problem and determine
how you can implement the required capabilities in an incremental manner.
Learn how to document errors:
· they must be repeatable;
· the code should be short;
· collect hardcopy of the program, the compile, and the test run.
Human memory is fallible, and computers are unforgiving, so no one will believe you if
you don’t have documentation. Experts can’t help you if you come in with a folktale —
“I tried that, but it gave me an error.” You must be able to replicate the error.
If you encounter an error that you can’t understand, then keep the code which generated
the error and find out what was wrong. You may produce a working program by trying
another approach, but if you don’t know why you got the error, then there’s a gap in your
knowledge of Java.
December 18th, 2009

C++ RYG Guess The Random Number Game + Source Code

C++ RYG Guess The Random Number

C++ RYG Guess The Random Number

Program description: Program to generate a random

number b/n 100 and 999 and accept users guess.

The user keeps guessing untill he guesses the random

number. The program gives the user a hint if he guessed

one of the digits but its one wrong place.

RED: you got a number wrong

YELLOW: you got a digit close

GREEN: you got a digit right

SOURCE PACKAGE

SOURCE FILE

DEMO GAME PLAY