Header (.h) files

Published on: March 29, 2011

In this tutorial, I show you how to use header files (.h files) in C++ with ease. Last time I showed you the index Sort used with void functions. This made the program much easier to read because it was more organized and the main program was much smaller. Using .h files will do the same by splitting up the program into two different files. A main.cpp file and a header.h file.

This is a very short tutorial that only shows how to break the program up. in my next video, I hope to show you how to use implementation files which are also .cpp files, to further break down the program and work with three different files. This is also a great way for data hiding in C++

Below you will find two section of codes, one for each file. Please read the comments on top of each section to know what file it is from, they are marked as header.h and main.cpp. If you have any questions about the program or anything in general relating to beginner C++ Programming, feel free to ask. I hope you enjoy the video and if you have any requests feel free to let me know.

Remember to checkout the Codesnip below to review the C++ code yourself! Feel free to copy the code, but I ask that you please provide credit if you leave the code unchanged when you use it.

Codesnip:

//Name:  Nazmus
//Program: Using header files(.h files)
//Website: EasyProgramming.net
//header.h

#include <iostream>

#include <string>

using namespace std;

void prompt(string name[3], int grade[3]);

void init(int index[3]);
void sort(string name[3], int index[3]);

void output(string name[3], int grade[3], int index[3]);



//Name:  Nazmus
//Program: Using header files(.h files)
//Website: EasyProgramming.net
//main.cpp

#include "header.h"

int main()
{

 string name[3];
 int grade[3];
 int index[3];

 prompt(name, grade);
 init(index);
 sort(name, index);

 output(name, grade, index);
}

void prompt(string name[3], int grade[3])
{

 for(int i=0;i<=2;i++)
 {
  cout << "Please enter name: ";

  cin >> name[i];
  cout << "Please enter grade: ";
  cin >> grade[i];
 }
}

void init(int index[3])
{ 
 for(int i=0;i<=2;i++)
 {

  index[i]=i;
 }

}

void sort(string name[3], int index[3])
{

 int i, j;
 for(i=0;i<=1;i++)
 {

  for(j=i+1;j<=2;j++)
  {
   int temp;

   
   if(name[index[i]] > name[index[j]])
   {

    temp = index[i];
    index[i] = index[j];

    index[j] = temp;
   }
  }
 }
}

void output(string name[3], int grade[3], int index[3])
{

 int i;
 cout << endl;

 for(i=0;i<=2;i++)
 { 
  cout << name[index[i]] << "        "

   << grade[index[i]] << endl;
 }

 cin.ignore();

 cin.get();

 //system("pause");
}



Comments: