Wednesday, 21 August 2013

Write A Program That Print its Own Code


#include<iostream.h>
#include<conio.h>


#include<fstream.h>
void main()
{
char c[40];
int ch;
cout<<"Enter 1 for Printing whole Programs code"<<endl<<"Press 2 to exit"<<endl;
cout<<"Enter choice"<<endl;cin>>ch;
switch (ch)
{
case 1:
ifstream in("t.cpp");
while (!in.eof())
{
in.getline(c,40);
cout<<"\n";
cout<<c;
 }
 break;
 case 2:
 break;
 }
getch();
}

Output  



                                                                 
Explanation :-


* #include<iostream.h> :- This is a Header file that contains definition for cout and cin functions
* #include<conio.h> :- This is also a Header File that contains defintion for getch ( ) function

* #include<fstream.h> :- This is also a Header File that contains definition for file stream functions . It contains definition for objects and functions required to read and write data to and from file.

* Switch Statement
In this program I have used Switch Statement . This switch statement consist of two cases . 
Case 1 :- It contains code to print current program source code
Case 2 :- It contains code to break execution of current program

* Logic Of  Program :- 


ifstream in("t.cpp");
while (!in.eof())
{
in.getline(c,40);
cout<<"\n";
cout<<c;
 }

* ifstream in("t.cpp");
First an Object in of ifstream is made ifstream is defined as class to read data from file . in is object of ifstream class .
Here we have given the name of current file as parameter to in object to read content of this file


* while (!in.eof())
In this line the loop continues untill EndOfFile occurs

* in.getline(c,40);
This line of code will get one line from file given in path and give data of file to 'c' variable

* cout<<c;
In this line of code I have printed data of c on to computer screen

Share this

0 Comment to "Write A Program That Print its Own Code"

Post a Comment