NAMESPACE EXAMPLE 1


1.  Namespaces STD example 1

In this example I will show you how to use a namespace std. The point of this exercise is to get familiar with std or standard template. Open a new project in you program like Dev C++ or Microsoft Visual Studio and name it “Namespace1” or as you like it. When you start you project enter the code given below. I should tell you that in Win32 wizard just click next and then Finish.
// Namespace1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
            cout << "This program is awesome." << endl;
            return 0;
}

When you entered this program code debug it. When you debug this code the debugger will tel you that There were build errors. He will ask you would you like to continue and run the last successful build. Since this is the first building of your program there isn’t any working version so your program won’t work. Why? What is wrong?
The reason why your program doesn’t work is that you need a standard template library for input/output words. Since we used the words like cout and endl in you program code your program won’t work unless you enter standard template library.
Now correct your program entering the following code below the #include <iosream>.
using std::cout;
using std::endl;
Now the program code should look like this
// Namespace1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;

int _tmain(int argc, _TCHAR* argv[])
{
            cout << "This program is awesome." << endl;
            return 0;
}

After you debug your program code the program should be working unless you failed entering correct program code. Press the Ctrl+F5 to run your program. The function of this program is to show the following sentence: “This program is awesome.” The result is shown in next figure.

There is another way for activating standard template library by entering the following code.

using namespace std;

If you enter this code line into your program the program code should look like this.

// Namespace1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
            cout << "This program is awesome." << endl;
            return 0;
}

The program will work properly.
With this program line we have saved time because we don’t need to activate each of the commands separately. By commands I mean the cout, cin or endl. We have saved some time by using just one command line and that is using namespace std;.
Share on Google Plus