Need a project done?

C++ Programming Developer

Search This Blog

Mouse Handling in C++

Following is the program for mouse handling in C++ when user left clicks.

#include <iostream>
using namespace std;

Dynamically allocate memory in C++

Dynamically allocate memroy in C++ using following program:


#include <iostream>
using namespace std;

Stack using linked list in C++


Stack using linked list in C++ program is given below:

//Stack using linked list in C++ using templates
#include <iostream>
using namespace std;

Stack using Link List in C++

Program to create a stack using link list in C++.

//Stack using Link List in C++
#include <iostream>
using namespace std;

Stack in C++ | Program to create a stack in C++

Stack in C++ program is given below:

//Stacks in C++
#include <iostream>
using namespace std;

Swap without using variable - C++


Swap two values without using a variable in C++ program is given below:

//Program to swap 2 numbers without using a variable in C++.
#include <iostream>
using namespace std;

Binary Tree in C++


Binary Tree program in C++ is given below:

See First: Binary Tree in C++ (A relatively easier Binary Tree program)

// Binary Tree in C++
// Binary Tree program to insert generically in the binary tree.

#include "stdafx.h" //Comment This line if it creates error.
#include <iostream>
using namespace std;

Printing Linked List Recursively in C++

Printing Linked List Recursively in C++ Program is given below:


// Printing Linked List Recursively in C++
// Linked List is created by inserting at head and then printing recursively.
#include <iostream>
using namespace std;

Operator Overloading: Overload << and >> operator


Overload << and >> operator program is given below:

// operator overloading
// overloading << and >> operator
#include "stdafx.h" //Delete this line if it creates error
#include <iostream>
using namespace std;
const int LEN = 80;           //maximum length of names
////////////////////////////////////////////////////////////////
class employee                        //employee class
{
private:
char name[LEN];                 //employee name
unsigned long number;
public:
friend istream& operator >> (istream& s, employee& e);
friend ostream& operator << (ostream& s, employee& e);
};
//-------------------------------------------------------------
istream& operator >> (istream& s, employee& e){
cout << "Name: "; s.getline(e.name,LEN,'\n');
cout << "Number: "; s >> e.number;
return s;
}
//-------------------------------------------------------------
ostream& operator << (ostream& s, employee& e){
cout << "Name: " << e.name << endl
<< "Number: " << e.number << endl;
return s;
}
///////////////////////////////////////////////////////////////
int main(){
employee oe; // oe => object of class employee.
cin >> oe;
cout << oe;
return 0;
}

Printing Linked List in Reverse Order Recursively in C++


Printing Linked List in Reverse Order Recursively in C++ Program is given below:

// Printing Linked List in Reverse Order Recursively in C++
// Insertion at head is done in the following program
#include <iostream>
using namespace std;

////////////////////////////////////////////////////////////////
struct link                           //one element of list
{
int data;                          //data item
link* next;                        //pointer to next link
};
////////////////////////////////////////////////////////////////
class linklist                        //a list of links
{
private:
link* first;                    //pointer to first link also known as head.
public:
linklist()                      //no-argument constructor
{ first = NULL; }            //no first link
link* getHead(){ return first; }
void additem(int d);            //add data item (one link)
void displayRecursivelyReversed(link* current);                 //display all links in REVERSE ORDER.
};
//-------------------------------------------------------------void
void linklist::additem(int d)         //add data item
{
link *newLink = new link;
newLink->data = d;
//insert at head
newLink->next = first;
first = newLink;
}
//-------------------------------------------------------------void
void linklist::displayRecursivelyReversed(link* current)              //display all links
{
if (current != NULL){
//move to next node.
displayRecursively(current->next);
cout << current->data << endl;
}

}
////////////////////////////////////////////////////////////////
int main()
{
linklist li;       //make linked list
li.additem(25);    //add four items to list
li.additem(36);
li.additem(49);
li.additem(64);
li.displayRecursivelyReversed(li.getHead());      //display entire list
return 0;
}

Linked List using Templates in C++


Linked List using Templates in C++ program is given below:


// linkedlist.cpp
// linked list using templates
// See also: Link List program in C++

#include "stdafx.h" //Remove this line if you see any error.
#include <iostream>
using namespace std;

////////////////////////////////////////////////////////////////
template <typename T>
struct link                           //one element of list
{
T data;                          //data item
link* next;                        //pointer to next link
};
////////////////////////////////////////////////////////////////
template <class T>
class linklist                        //a list of links
{
private:
link<T>* first;                    //pointer to first link
public:
linklist()                      //no-argument constructor
{ first = NULL; }            //no first link
void additem(T d);            //add data item (one link)
void display();                 //display all links
};
//-------------------------------------------------------------void
template <class T>
void linklist<T>::additem(T d)         //add data item
{
link<T> *newLink = new link<T>;
newLink->data = d;
//insert at head of link list
newLink->next = first;
first = newLink;
}
//-------------------------------------------------------------void
template <class T>
void linklist<T>::display()              //display all links
{
link<T>* current = first;             //set ptr to first link
while( current != NULL )           //quit on last link
{
cout << current->data << endl;  //print data
current = current->next;        //move to next link
}
}
////////////////////////////////////////////////////////////////

int main()
{
linklist<int> li;       //make linked list
li.additem(25);    //add four items to list
li.additem(36);
li.additem(49);
li.display();      //display entire list

linklist<char> lch;      //make linked list
lch.additem('a');    //add four items to list
lch.additem('b');
lch.additem('c');
lch.display();      //display entire list

return 0;
}

Binary Tree in C++

Binary Tree in C++ Program is given below:
// Binary Tree in C++
// A very basic Binary Tree program in C++

#include "stdafx.h" //Comment this line if it creates any error.
#include <iostream>
using namespace std;
//////////////////////////////////////////////////////////////
struct nodeType{
nodeType();
int info;
nodeType* father;
nodeType* left;
nodeType* right;
};
nodeType::nodeType(){
father = left = right = NULL;
}
//////////////////////////////////////////////////////////////
class binaryTree{
public:
binaryTree(){  root = NULL; }
//------------------------------------------------------------
nodeType* makeTree(int x){
nodeType* p = new nodeType;
p->info = x;
p->father = NULL;
p->right = NULL;
p->left = NULL;
root = p;
return p;
}
//------------------------------------------------------------
void setLeft(nodeType* p, int x){
if (p == NULL){
cout << "Void Insertion!" << endl;
}
else if (p->left != NULL){
cout << "Invalid Insertion" << endl;
}
else{
p->left = new nodeType;
p->left->info = x;
p->left->right = NULL;
p->left->left = NULL;
p->left->father = p;
}
}
//------------------------------------------------------------
void setRight(nodeType* p, int x){
if (p==NULL){
cout << "Void Insertion" <<endl;
}
else if (p->right != NULL){
cout << "Invalid Insertion" << endl;
}
else{
p->right = new nodeType;
p->right->info = x;
p->right->left = NULL;
p->right->right = NULL;
p->right->father = p;
}
}
//------------------------------------------------------------
nodeType* getRoot(){
return root;
}
//------------------------------------------------------------
void print(nodeType* p){
cout << p->info << endl;

if (p!=NULL && p->left == NULL && p->right == NULL)
return ;
if (p!=NULL && p->left != NULL && p->right == NULL)
print (p->left);
if (p!=NULL && p->left == NULL && p->right != NULL)
print (p->right);
if (p!=NULL && p->left != NULL && p->right != NULL){
print (p->left);
print (p->right);
}
}

//----------------------------------------------------------------
//----------------------------------------------------------------
private:
nodeType* root;
};
//////////////////////////////////////////////////////////////
int main(){
binaryTree obj;
        // We insert 3 nodes in Binary Tree. You can try inserting more
obj.makeTree(5);
obj.setLeft(obj.getRoot(),4);
obj.setRight(obj.getRoot(),6);
obj.print(obj.getRoot());
return 0;
}


Now see Generic Binary Tree in C++ Program to insert at the correct position in the binary tree.

Link List program in C++

Link List Program in C++ is given below:

// linklist.cpp
// linked list program in C++
// Compiler: Microsoft Visual Studio 2012

#include "stdafx.h"
#include <iostream>
using namespace std;

////////////////////////////////////////////////////////////////
struct link                           //one element of list
{
int data;                          //data item
link* next;                        //pointer to next link
};
////////////////////////////////////////////////////////////////
class linklist                        //a list of links
{
private:
link* first;                    //pointer to first link
public:
linklist()                      //no-argument constructor
{ first = NULL; }            //no first link
void additem(int d);            //add data item (one link)
void display();                 //display all links
};
//-------------------------------------------------------------void
void linklist::additem(int d)         //add data item
{
link *newLink = new link;
newLink->data = d;
//insert at head
newLink->next = first;
first = newLink;
}
//-------------------------------------------------------------void
void linklist::display()              //display all links
{
link* current = first;             //set ptr to first link
while( current != NULL )           //quit on last link
{
cout << current->data << endl;  //print data
current = current->next;        //move to next link
}
}
////////////////////////////////////////////////////////////////
int main()
{
linklist li;       //make linked list
li.additem(25);    //add four items to list
li.additem(36);
li.additem(49);
li.additem(64);
li.display();      //display entire list
return 0;
}

See also: Link list using Templates

Reading link list from File in C++

To Read a link list from file, we've adopted the following procedure:
1. Write each node individually to a file in the function of getData().
2. Read Each node from file one by one and insert it in the link list .


//Reading link list from File in C++

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <Windows.h>
using namespace std;

class linkList{
public:
void getData();
void insert(linkList **head, linkList **tail); // insert at tail
void printAll(linkList *head); // Display all records.
private:
char name[100];
int rollNo;
linkList *next;
};
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::getData(){
cout << "Enter Name: "; cin >> name;
cout << "Enter Roll Number: "; cin >> rollNo;
next = NULL;
ofstream os("nodes of my link list.dat", ios::binary | ios::out | ios::app);
os.write( reinterpret_cast <char*> (this), sizeof(*this) );
os.close();
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::insert(linkList **head, linkList **tail){ // insert at tail
if (*head == NULL && *tail == NULL){
*head = (this);
*tail = (this);
}
else{
(*tail)->next = this;
*tail = this;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::printAll(linkList *head){
for (linkList *temp = head; temp!=NULL; temp=temp->next){
cout << "Name: " << temp->name << endl
<<  "Roll Number: " << temp->rollNo << endl << endl;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
/////////////////////////////////////////////////// Main() //////////////////////////////////////
int main(){
linkList *pointerOfLinkList  = 0, *head = 0, *tail = 0;

ifstream is;
while (true){
cout << "1. Insert Node\n"
<< "2. Print All\n"
<< "0. Press IT to load link list from file.\t";
int opt; cin >> opt;

switch(opt){
case 1:
pointerOfLinkList = new linkList;
pointerOfLinkList->getData();
pointerOfLinkList->insert(&head,&tail);
cout << "Inserted" << endl;
break;
case 2:
pointerOfLinkList->printAll(head);
break;
case 8:
break;
case 9:
break;
case 0:
is.open("nodes of my link list.dat", ios::binary | ios::in);

pointerOfLinkList = new linkList;
is.read(reinterpret_cast<char*>(pointerOfLinkList),sizeof(*pointerOfLinkList));
while (!is.eof()){
pointerOfLinkList->insert(&head,&tail);
pointerOfLinkList = new linkList;
is.read(reinterpret_cast<char*>(pointerOfLinkList),sizeof(*pointerOfLinkList));
}
is.close();
break;
default:
cout << "Wrong Key pressed" << endl;
}
_getch();
system("cls");
}
return 0;
}

Insert at tail Link List


//Program to insert at tail in Link List using Classes.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>
#include <Windows.h>
using namespace std;

class linkList{
public:
void getData();
void insert(linkList **head, linkList **tail); // insert at tail
void printAll(linkList *head); // Display all records.
private:
char name[100];
int rollNo;
linkList *next;
};
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::getData(){
cout << "Enter Name: "; cin >> name;
cout << "Enter Roll Number: "; cin >> rollNo;
next = NULL;
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::insert(linkList **head, linkList **tail){ // insert at tail
if (*head == NULL && *tail == NULL){
*head = (this);
*tail = (this);
}
else{
(*tail)->next = this;
*tail = this;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
void linkList::printAll(linkList *head){
for (linkList *temp = head; temp!=NULL; temp=temp->next){
cout << "Name: " << temp->name << endl
<<  "Roll Number: " << temp->rollNo << endl << endl;
}
}
//````````````````````````````````````````````````````````````````````````````````````````````````````````````
/////////////////////////////////////////////////// Main() //////////////////////////////////////
int main(){
linkList *pointerOfLinkList  = 0, *head = 0, *tail = 0;


while (true){
cout << "1. Insert Node\n"
<< "2. Print All\n"
<< "0. Exit\t";
int opt; cin >> opt;

switch(opt){
case 1:
pointerOfLinkList = new linkList;
pointerOfLinkList->getData();
pointerOfLinkList->insert(&head,&tail);
cout << "Inserted" << endl;
break;
case 2:
pointerOfLinkList->printAll(head);
break;
case 8:
break;
case 9:
break;
case 0:
return 0;
default:
cout << "Wrong Key pressed" << endl;
}
_getch();
system("cls");
}
return 0;
}

Initialize Static Array in C++


Initialize Static Array in C++ program is given below:

#include <iostream>
using namespace std;

class myClass{
private:
static int array[100]; //Static Array in C++
public:
void display();
};
////////////////////////////////////////////////////////////////
int myClass::array[100] = {0}; //Initialize Static Array in C++

void myClass::display(){
for (int i = 0; i<100; i++){
cout << "array[" << i << "] = " << array[i] << endl;
}
}
//``````````````````````````````````````````````````````````````

int main(){
myClass obj;
obj.display();
return 0;
}

Convert int to string C++

Convert int to string in C++. Following program converts an int to string in C++.
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string int_to_string(const int& port) {
    stringstream ss;
    ss << port;
    return ss.str();
}

int main() {
    int port = 114;
    cout << int_to_string(port) << endl;
}

Printing random lines from file C++

Printing random lines from file in C++ program is given below:

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
using namespace std;

int main(){
ofstream os("a.txt");
for (int i = 0; i<=999; i++){
os << i << endl;
}
os.close();

ifstream is("a.txt");

char c;
string line;
while (!is.eof()){
while (c != '\n'){
is.seekg(rand()%1000);
c = is.get();
}
getline(is,line);
cout << line << endl; //Printing lines randomly from file.
c = '0';
Sleep(300);
}
return 0;
}


Though lines are being printed randomly but there is repetition.

Copy one file to another file C++

'Copy one file to another file in C++' program is given below.
You have to write copy c:/source.txt c:/destination.txt to copy contents of file source.txt to destination.txt.

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

void Write(string, string);

int main(){
cout << "Write: copy srcfile destfile.cpp\nYou can give complete path as well.\n\n";
string s1, s2, s3;
cin >> s1 >> s2 >> s3;
if (strcmp(s1.c_str(),"copy") != 0){
cout << s1 << " is not a valid command. Only valid command for this program is copy." << endl;
}
Write(s2,s3);
return 0;
}
void Write(string s1, string s2){
char line[100];
ifstream is(s1.c_str());
ofstream os(s2.c_str());

if (is.is_open() && os.is_open()){
while (!is.eof()){
is.getline(line,100,'\n');
os << line << endl;
}
}
else{
if (!is.is_open()){
cout << endl << s1 <<" couldn't be opened. Creat and write something in a.txt, and try again." << endl;
}
else{
cout << endl << s2 <<" couldn't be opened. Creat and write something in a.txt, and try again." << endl;
}
}
}

Visit a simpler program:

Copy contents of One File to another C++

'Copy file in C++' program is given below.
Copies content of file 'a' to file 'b'.

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

int main(){
char line[100];

ifstream is("a.txt");
ofstream os("b.txt");

if (is.is_open()){
while (!is.eof()){
is.getline(line,100,'\n');
os << line << endl;
}
}
else{
cout << "a.txt couldn't be opened. Creat and write something in a.txt, and try again." << endl;
}

return 0;
}

See a better program:
Copy one file to another file C++

Finding a word from File C++


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

int main(){
ofstream os("test.txt");
os << "1. Hi." << endl <<"2. By mom!" << endl << endl << "4. YES I did it." << endl << "5. I'm fine." << endl << "6. I'm writing different lines to the file, OK?";

os.close();

cout << "My file contains following data:\n";
cout << "1. Hi." << endl <<"2. By mom!" << endl << endl << "4. YES I did it." << endl << "5. I'm fine." << endl << "6. I'm writing different lines to the file, OK?";

cout << "\n\nEnter a word to find from it: ";
char word[50]; cin.getline(word,50,'\n');

//Calculating number of characters in word.
for ( int sizeOfWord = 0; word[sizeOfWord]!='\0'; sizeOfWord++);

//searching the word.
ifstream is("test.txt");

char sentence[200];
int line_no = 1;
int i = 0;
bool found = false;
while (!is.eof()){
is.getline(sentence,200,'\n');

for (int j = 0; sentence[j]!='\0'; j++){
if (sentence[j] == word[i]){
++i;
}
else{
i = 0;
}
if (i >= sizeOfWord){
cout << "Found at line: " << line_no << endl;
found = true;
}
}

line_no++;
}
if (!found){
cout << "NOT found." << endl;
}
return 0;
}

Reading Random lines from a text file C++


Calculate Time of program C++

Time in C++:
Following program calculates time of program execution in C++:

 #include <iostream>  
 #include <ctime>  
 #include <windows.h>  
 using namespace std;  
   
 int main(){  
      double start_time = clock();  
      Beep(500,1000); //BEEP FOR 1 SECOND will be produced. //YOUR CODE HERE.  
      double end_time = clock();  
        
   
      double time_taken = end_time - start_time;  
      double time_taken_in_seconds = time_taken/CLOCKS_PER_SEC;  
   
      cout << "Time taken during program execution is " << time_taken_in_seconds << " Second(s)"<< endl;  
        
      return 0;  
 }  

Sorting Linked List C++

'Sorting linked list in ascending order' program is given below:


#include <iostream>
using namespace std;
/////////////////////////////////////////////////////////////////////////////////////////////
struct node{
int data;
node *next;
};
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
class ll{
public:
ll();
void insert();
void print();
private:
node *head, *tail;
};
/////////////1////////////////////////////////////////////////////////////////////////////////
ll::ll(){
head = tail = 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ll::insert(){
node *temp = new node;
temp->next = NULL;
cout << "Id: ";  cin >> temp->data;
if (head == 0 && tail == 0){
head = temp;
tail = temp;
}
else{
if (temp->data <= head->data){
//Insert at head
temp->next = head;
head = temp;
}
else{
if (temp->data >= tail->data){
//insert at tail
tail->next = temp;
tail = temp;
}
else{// Insert some where in the middle.
node *p = head;
while (temp->data > p->data){//finding where to insert.
p = p->next;
}
//we've to insert at node before p.
//so
for (node *b = head; b->next != p; b = b->next);
//insert after bth node.
temp->next = b->next;
b->next = temp;
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
void ll::print(){
for (node *p = head; p!=NULL; p=p->next){
cout << p->data << endl;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
//*******************************************************************************************
int main(){
ll o;
cout << "Do you want to insert? (y/n)  "; char opt; cin >> opt;

while (opt == 'y' || opt == 'Y'){
o.insert();
cout << "Do you want to insert? (y/n)  "; cin >> opt;
}

o.print();

return 0;
}
//*******************************************************************************************

Wacmian Numbers program C++


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

int getInt(char);

int main(){
long int sum[100] = {0};
int u = 0;
char a[100] = "";
cout << "WACMIAN Number: "; cin >> a;

while (a[0]!='#' || a[1] != '\0'){


if (a[0] != '#' || a[1] != '\0'){

for (int j = 0; a[j]!= '\0'; j++);
j--;

for (int i = j, base = 0; i >= 0; i--, base++){
sum[u] += getInt(a[i])*pow(6,base);
}
if (a[0] != '#')
u++;
}
cout << "WACMIAN Number: "; cin >> a;
}

cout << endl << "OUTPUT:\n";
for (int i =0; i <= u; i++){
if (a[0] == '#' && sum[i] == 0 && i==u)
break;
cout << sum[i] << endl;
}


return 0;
}

int getInt(char u){
switch (u){
case '%':
return 0;
case ')':
return 1;
case '~':
return 2;
case '@':
return 3;
case '?':
return 4;
case '\\':
return 5;
case '$':
return -1;
default:
cout << "Wrong input." << endl;
exit(0);
}
}

Sound in C++


#include <windows.h>

int main()
{
    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1568, 200);
    Beep(1245, 1000);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1397, 200);
    Beep(1175, 1000);
   
    return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <iostream.h>
#include <windows.h>

void scale(void)
{ Beep(523,400); // 523 hertz (C5) for 400 milliseconds
 Beep(587,400);
 Beep(659,400);
 Beep(698,400);
 Beep(784,400);
 Beep(698,400);
 Beep(659,400);
 Beep(587,400);
 Beep(523,400);
}


int main()
{

 scale();
 cout << "Scale completed.\n";
 
 return 0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




Reading Writing from Linked List C++



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



struct link{
int data;
link* next;
};

class linkedList{
public:
linkedList();
void addItem(int);
void print(void);
private:
link* head;
link* tail;
};

linkedList::linkedList(){
head = tail = NULL;
}

void linkedList::addItem(int n){
link* temp = new link;
temp->data = n;
temp->next = 0;

if (head == 0 && tail == 0){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
ofstream os("linkedList.txt", ios::out | ios::app);
os << "data: " << temp->data << endl;
os.close();
}

void linkedList::print(){
for (link* p = head; p != NULL; p = p->next){
cout << p->data << endl;
}
}

int main(){
ofstream os("linkedList.txt");
os.close();

int n;  
linkedList ll;
cout << "Enter number to insert: (-1 to print): "; cin >> n;

while (n!=-1){
ll.addItem(n);
cout << "Enter number to insert: (-1 to print): "; cin >> n;
}
   
ll.print();

cout << "Linked List has been written in the file and has been printed\nNow printing link List's data using file." << endl;

//READING LINKED LIST FROM FILE.
//////////////
// linkedList LL;
char str;
ifstream is;
is.open("linkedList.txt");
while (is){
is.get(str);
cout << str;
}
is.close();
return 0;
}

Inheritance example C++


#include <iostream>
using namespace std;

class cc{

};

class m:  public cc{
public:
void f(){
cout << "m" << endl << endl;
}
};
class l:  public cc{
public:
void f(){
cout << "l" << endl << endl;
}
};
class v:  public cc{
public:
void f(){
cout << "v" << endl << endl;
}
};

class ll: public m, public l, public v{
};

int main(){
ll *p = new ll;

p->m::f();
return 0;
}

Throw class C++

Throw Class in C++ program is given below:

 #include <iostream>  
 //#include <string>  
 using namespace std;  
   
 class divByZero{};  //An empty CLASS.
   
 int main(){  
      try{  
      throw divByZero();  
      }  
      catch(divByZero){  
           cout << "divByZero caught in catch block" << endl;  
      }  
      return 0;  
 }  


Another throw Class in C++ program is given below:

 #include <iostream>  
 #include <string>  
 using namespace std;  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 class divByZero{  
 public:  
      divByZero();  
      divByZero(string);  
      string what();  
 private:  
      string message;  
 };  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 divByZero::divByZero(){  
      message = "Division by Zero IS NOT possbile";  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 divByZero::divByZero(string s){  
      message = s;  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 string divByZero::what(){  
      return message;  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 int main(){  
      try{  
      throw divByZero();  
      }  
      catch(divByZero s){  
           cout << "divByZero caught in catch block" << endl;  
             
           cout << s.what() << endl;  
      }  
      return 0;  
 }  


Another throw Class in C++ program is given below:
 #include <iostream>  
 #include <string>  
 using namespace std;  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 class divByZero{  
 public:  
      divByZero();  
      divByZero(string);  
      string what();  
 private:  
      string message;  
 };  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 divByZero::divByZero(){  
      message = "Division by Zero IS NOT possbile";  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 divByZero::divByZero(string s){  
      message = s;  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 string divByZero::what(){  
      return message;  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 void dosomething();  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 int main(){  
      dosomething();  
      cout << "Control Comes back in main" << endl;  
      return 0;  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  
 void dosomething(){  
      try{  
      throw divByZero();  
      cout << "Control Doesn't come back HERE" << endl;   
      }  
      catch(divByZero s){  
           cout << "divByZero caught in catch block" << endl;  
             
           cout << s.what() << endl;  
      }  
 }  
 /////////////////////////////////////////////////////////////////////////////////////////////////  

Linked List Write in file C++


 #include <iostream>  
 #include <fstream>  
 using namespace std;  
   
 ofstream os("linkedList.txt",ios::binary);  
   
 struct link{  
  int data;  
  link* next;  
 };  
   
 class linkedList{  
 public:  
  linkedList();  
  void addItem(int);  
  void print(void);  
 private:  
  link* first;  
 };  
   
 linkedList::linkedList(){  
  first = NULL;  
 }  
   
 void linkedList::addItem(int n){  
  link* temp = new link;  
  temp->data = n;  
  temp->next = first;  
  first = temp;  
  os.write(reinterpret_cast<char*>(temp),sizeof(temp));  
 }  
   
 void linkedList::print(){  
  for (link* p = first; p != NULL; p = p->next){  
  cout << p->data << endl;  
  }  
 }  
   
 int main(){  
  int n;   
   
  linkedList ll;  
   
  do{  
  cout << "Enter number to insert: (-1 to print): "; cin >> n;  
    
  ll.addItem(n);  
  } while (n != -1);  
    
  ll.print();  
  return 0;  
 }  

Exception bad_alloc C++


1:  #include <iostream>  
2:  using namespace std;  
3:  #include <string>  
4:    
5:  int main(){  
6:       int *list[100];  
7:    
8:       try{  
9:            for (int i = 0; i<100; i++){  
10:                 list[i] = new int[50000000];  
11:                 cout << "Created List[" << i << "] of 50000000 components." << endl;  
12:            }  
13:       }  
14:       catch(bad_alloc be){  
15:            cout << "In the bad_alloc catch bloc: " << be.what() << endl;  
16:       }  
17:       return 0;  
18:  }  

Exception out_of_range C++


1:  #include <iostream>  
2:  using namespace std;  
3:  #include <string>  
4:    
5:  int main(){  
6:       string sentence;  
7:       string str1, str2, str3;  
8:    
9:       try{  
10:            sentence = "Testing string exceptions!";  
11:            cout << "Sentence = " << sentence << endl;  
12:            cout << "sentence.lenght() = " << static_cast<int>(sentence.length()) << endl;  
13:            str1 = sentence.substr(8,20);  
14:            cout << "str1 = " << str1 << endl;  
15:            str2 = sentence.substr(28,10);  
16:            cout << "str2 = " << str2 << endl;  
17:            str3 = "Exception handling. " + sentence;  
18:            cout << "str3 = " << str3 << endl;  
19:            cout << "str3.length() = " << str3.length() << endl;  
20:       }  
21:    
22:       catch (out_of_range re){  
23:            cout << "In the out_of_range catch block: " << re.what() << endl;  
24:       }  
25:       catch(length_error le){  
26:            cout << "In the length error code block: " << le.what() << endl;  
27:       }  
28:    
29:       return 0;  
30:  }  

Linked list using Classes

Linked List using Classes program is given below:
Insert at head.

1:  #include <iostream>  
2:  using namespace std;  
3:  //////////////////////////////////////////////////////////////////////////////////////////////////  
4:  //////////////////////////////////////////////////////////////////////////////////////////////////  
5:  template <class TYPE>  
6:  struct link{//Within this struct definition 'link' means link<TYPE>  
7:       TYPE data;  
8:       link* next;  
9:  };  
10:  //////////////////////////////////////////////////////////////////////////////////////////////////  
11:  //////////////////////////////////////////////////////////////////////////////////////////////////  
12:  template <class TYPE>  
13:  class ll{//ll => linked list  
14:       private:  
15:            link<TYPE> *first;  
16:       public:  
17:            ll();  
18:            void addItem(TYPE);  
19:            void display();  
20:  };  
21:  //////////////////////////////////////////////////////////////////////////////////////////////////  
22:  template <class TYPE>  
23:  ll<TYPE>::ll(){  
24:       first = NULL;  
25:  }  
26:  //////////////////////////////////////////////////////////////////////////////////////////////////  
27:  template <class TYPE>  
28:  void ll<TYPE>::addItem(TYPE n){  
29:       link<TYPE>* temp= new link<TYPE>;  
30:       temp->data = n;  
31:       temp->next = first;  
32:       first = temp;  
33:  }  
34:  //////////////////////////////////////////////////////////////////////////////////////////////////  
35:  template <class TYPE>  
36:  void ll<TYPE>::display(){  
37:       link<TYPE>* p = first;  
38:       for (; p!= NULL; p=p->next){  
39:            cout << p->data << endl;  
40:       }  
41:  }  
42:  //////////////////////////////////////////////////////////////////////////////////////////////////  
43:  //////////////////////////////////////////////////////////////////////////////////////////////////  
44:  //template <class TYPE>  
45:  int main(){  
46:       ll<char> l;  
47:       char n;  
48:       do{  
49:            cout << "NUMBER: (n to exit)";          cin >> n;  
50:            l.addItem(n);  
51:       }  
52:       while (n!='n');  
53:       l.display();  
54:       return 0;  
55:  }  

Linked List using Classes


Linked List using Classes program is given below:

1:  #include <iostream>  
2:  using namespace std;  
3:  //////////////////////////////////////////////////////////////////////////////////////////////////  
4:  //////////////////////////////////////////////////////////////////////////////////////////////////  
5:  template <class TYPE>  
6:  struct link{  
7:       TYPE data;  
8:       link* next;  
9:  };  
10:  //////////////////////////////////////////////////////////////////////////////////////////////////  
11:  //////////////////////////////////////////////////////////////////////////////////////////////////  
12:  template <class TYPE>  
13:  class linkList{  
14:  private:  
15:       link<TYPE>* first;  
16:  public:  
17:       linkList()  
18:       { first = NULL; }  
19:       void addItem(TYPE d);  
20:       void display();  
21:  };  
22:  //////////////////////////////////////////////////////////////////////////////////////////////////  
23:  //////////////////////////////////////////////////////////////////////////////////////////////////  
24:  template <class TYPE>  
25:  void linkList<TYPE>::addItem(TYPE d){  
26:       link<TYPE> *temp = new link<TYPE>;  
27:       temp->data = d;  
28:       temp->next = NULL;  
29:       if (first == NULL){  
30:            first = temp;  
31:       }  
32:       else{  
33:            temp->next = first;  
34:            first = temp;  
35:       }  
36:  }  
37:  //////////////////////////////////////////////////////////////////////////////////////////////////  
38:  template <class TYPE>  
39:  void linkList<TYPE>::display(){  
40:       link<TYPE> *p = first;  
41:       for (int i = 0; p!=NULL; p = p->next){  
42:            cout << p->data << endl;  
43:       }  
44:  }  
45:  //////////////////////////////////////////////////////////////////////////////////////////////////  
46:  //////////////////////////////////////////////////////////////////////////////////////////////////  
47:  int main(){  
48:       linkList<double> l;//Here you can write char, int, etc.  
49:       char opt;  
50:       do{  
51:            cout << "Number: ";          int n;          cin >> n;  
52:            l.addItem(n);  
53:            cout << "Do you want to insert any other item? (y/n) ";     cin >> opt;  
54:       }  
55:       while (opt == 'y');  
56:       l.display();  
57:       return 0;  
58:  }  

Template C++

Simple example of Template in C++.

1:  #include <iostream>  
2:  using namespace std;  
3:  template <class dT>  
4:  void swapIt(dT &u, dT &v);  
5:    
6:  int main(){  
7:       int i1 = 2, i2 = 4;  
8:       double d1 = 2.2, d2 = 5.6;  
9:       float f1 = 1.1, f2 = 5.2;  
10:       char c1 = 'c', c2 = 'R';  
11:       cout << "i1 = " << i1 << "\ti2 = " << i2 << endl;  
12:       cout << "d1 = " << d1 << "\td2 = " << d2 << endl;  
13:       cout << "f1 = " << f1 << "\tf2 = " << f2 << endl;  
14:       cout << "c1 = " << c1 << "\tc2 = " << c2 << endl;  
15:         
16:       swapIt(i1,i2);  
17:       swapIt(f1,f2);  
18:       swapIt(d1,d2);  
19:       swapIt(c1,c2);  
20:    
21:       cout << "\nAfter swaping: " << endl;  
22:       cout << "i1 = " << i1 << "\ti2 = " << i2 << endl;  
23:       cout << "d1 = " << d1 << "\td2 = " << d2 << endl;  
24:       cout << "f1 = " << f1 << "\tf2 = " << f2 << endl;  
25:       cout << "c1 = " << c1 << "\tc2 = " << c2 << endl;  
26:       return 0;  
27:  }  
28:  template <class dT>  
29:  void swapIt(dT &u, dT &v){  
30:       dT t = u;  
31:       u = v;  
32:       v = t;  
33:  }  

Find a particular person from file C++

C++ Program to find a particular person from a file using file handling.

1:  #include <iostream>  
2:  #include <fstream>  
3:  using namespace std;  
4:    
5:  /////////////////////////////////////////////////////////////////////////////////////////////////  
6:  class person{  
7:  protected:  
8:       char name[80];  
9:       short age;  
10:  public:  
11:       void getData(){  
12:            cout << "Enter name: "; cin.ignore(); cin.getline(name,80,'\n');   
13:            cout << "Enter age: "; cin >> age;   
14:       }  
15:       void showData(){  
16:            cout << "Name: " << name << endl;  
17:            cout << "Age: " << age << endl;  
18:       }  
19:  };  
20:  /////////////////////////////////////////////////////////////////////////////////////////////////  
21:  int main(){  
22:       person pers;  
23:       fstream fs("person.dat", ios::in | ios::out | ios::binary);  
24:       char opt;  
25:       do{  
26:            cout << "\nEnter person's data:\n";  
27:            pers.getData();  
28:            fs.write(reinterpret_cast<char*>(&pers),sizeof(person));  
29:            cout << "Any other person left? (y/n) "; cin >> opt;  
30:       }  
31:       while (opt == 'y');  
32:         
33:       cout << "\n\nWhich person's data do you want to get? "; int n; cin >> n;  
34:       fs.seekg(0,ios::end);  
35:       int endPosition = fs.tellp();  
36:       int totalPersons = endPosition/sizeof(person);  
37:       cout << "Total Persons are: " << totalPersons << endl;  
38:         
39:       fs.seekg((n-1)*sizeof(person));  
40:       fs.read(reinterpret_cast<char*>(&pers),sizeof(person));  
41:       pers.showData();  
42:         
43:       return 0;  
44:  }  

Input/Output with Multiple Objects C++


Write Objct to File C++

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

/////////////////////////////////////////////////////////////////////////////////////////////////
class person{
protected:
char name[80];
short age;
public:
void getData(){
cout << "Enter name: "; cin.getline(name,80,'\n');
cout << "Enter age: "; cin >> age;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////

int main(){
person pers;
pers.getData();

//open file.
ofstream os("PERSON.DAT", ios::binary);
//write this object to file.
os.write(reinterpret_cast<char*>(&pers), sizeof(person));
cout << "FILE WRITTEN" << endl;
return 0;
}

Now

Read Object from File C++

Read Object from File C++

After an object has been written in a file, you can read that object from file in C++.
I've written an object at Write Objct to File C++.

After writing this object, following is the program to read an object from a file.

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

/////////////////////////////////////////////////////////////////////////////////////////////////
class person{
protected:
char name[80];
short age;
public:
void showData(){
cout << "Name: " << name << endl;
cout << "Age: " <<  age << endl;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////

int main(){
person pers;

//open file.
ifstream is("PERSON.DAT", ios::binary);
//read an object from this file.
is.read(reinterpret_cast<char*>(&pers), sizeof(person));
//after reading object from file, Show it.
pers.showData();
return 0;
}

Write and read Object in file C++


Write and read Object in file in C++.

#include <iostream>
#include <fstream>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////
class person{
protected:
char name[80];
short age;
public:
void getData(){
cout << "Enter name: "; cin >> name;
cout << "Enter age: "; cin >> age;
}
void showData(){
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
////////////////////////////////////////////////////////////////////////////////////////////
int main(){
person pers;
pers.getData();
ofstream os("person.txt", ios::binary);//Open file in binary mode.
cout << "This data has been store in the file person.txt in directory you've created your project" << endl;
cout << "Now Enter this data again, this data will not be saved" << endl;
os.write(reinterpret_cast<char*>(&pers), sizeof(pers));
pers.getData();
os.close();

//PRINTING SAVED DATA IN FILE.
ifstream is("person.txt",ios::binary);
is.read(reinterpret_cast<char*>(&pers),sizeof(pers));
pers.showData();//Here the data saved in file should have been displayed, but it's showing data not saved in file. WHY?
return 0;
}
"Don't let anyone ever make you feel like you don't deserve what you want."