Friday, July 31, 2009

Write a program in C++ to write it's code?

I wanna write a program in C++ that prints it's code in the output.


a program that these two commands give a same conclution for it:


type program.cpp


program.exe


I don't wanna use system files. I wanna use ordinary commands of C++ , and I don't wanna play with files.


What should I do?

Write a program in C++ to write it's code?
You cannot get the source from the executable. This is because there are different ways of doing the same thing. Here is an example of that:





int i;


for(i = 0; i %26lt; 5; i++) {


cout %26lt;%26lt; i %26lt;%26lt; endl;


}





is the same thing as





int i = 0;


while(i %26lt; 5) {


cout %26lt;%26lt; i %26lt;%26lt; endl;


i++;


}





and to





int i = 0;


label: cout %26lt;%26lt; i %26lt;%26lt; endl;


i++;


if(i %26lt; 5) goto label;





The only way you can do this by printing out the original source file, which can be done as follows:





ifstream fin;


fin.open("program.cpp");


char s[80];


while(!fin.eof()) {


fin.getline(s, 80);


cout %26lt;%26lt; s %26lt;%26lt; endl;


}


fin.close();
Reply:this is one way





#include %26lt;dos.h%26gt; // the header which contains 'system' function





void main()


{


system("type program.cpp");


}





try it
Reply:20+ years ago, I had a homework assignment to do this. However, I had to do it in PL/C. It is possible, but being so long ago, I don't remember exactly how I did it. I remember it started with something like the following:





void main()


{


cout %26lt;%26lt; "void main()";


cout %26lt;%26lt; "{";


// Oops there's a problem here!!!


cout %26lt;%26lt; "}";


}





I have a memory of using an array of strings to store the values, rather than list them out individually. I also remember that each token was in two places: as a command in the program and within the string, so when I discovered a mistake, I needed to correct it in two places.





I was taking an automata theory at the time. Our instructor had us do this exercise to demonstrate the principle of proving things about turing machines by having a program execute itself. This technique is used to prove the halting problem.
Reply:Could you mean 'type program %26lt; program.cpp' as the command?


If so,








char c;


while (cin %26gt;%26gt; c) {


   %26amp;nbspcout %26lt;%26lt; c;


}





That will get whatever is in the file program.cpp to output, the screen.


No comments:

Post a Comment