How can I write a code to show itself (print code to console) using standard C++ only without any external library?
Asked
Active
Viewed 1,157 times
2 Answers
4
Tada: http://en.wikipedia.org/wiki/Quine_(computing)
On a slightly more pragmatic note, almost no one ever does this. It's pointless. If you want to distribute source code, just put it into a tarball or zip file like a sane person.

Chris Eberle
- 47,994
- 12
- 82
- 119
-
-
4
-
1Basically, the trick is to write your code so that it holds a string. Inside that string is the _exact same code_, except where the contents of the string would be (inside itself), you have some magic key character (or two) that is nowhere else in the code. You then display the string to the console until that key character, display the entire string, then display the string _after_ the key character. – Mooing Duck Oct 28 '11 at 21:59
1
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream sourceFile(__FILE__);
if (sourceFile.is_open())
{
while ( sourceFile.good() )
{
getline (sourceFile,line);
cout << line << endl;
}
sourceFile.close();
}
else cout << "Unable to open source file";
return 0;
}

Robᵩ
- 163,533
- 20
- 239
- 308

Fatih Donmez
- 4,319
- 3
- 33
- 45
-
Calling `good()`, `eof()`, &c as a loop condition almost always results in bugger programs. Hint: Why does your program print an extra blank line? – Robᵩ Oct 28 '11 at 22:04
-
2
-
1Typo: "bugger programs". I *meant* buggy programs. Not really the same. :) – Robᵩ Oct 28 '11 at 22:27