偶然听说了Quine,wikipedia上的解释是:
A quine is a non-empty computer program which takes no input and
produces a copy of its own source code as its only output. The
standard terms for these programs in the computability theory and
computer science literature are “self-replicating programs”,
“self-reproducing programs”, and “self-copying programs”.
纯属娱乐写了个C++版本:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char aDoubleQuot = 34;
string str[] = {
"#include <iostream>",
"#include <string>",
"using namespace std;",
"int main()",
"{",
" char a = 34;",
" string str[] = {",
" ",
" };",
" for (int i = 0; i <= 6;i++) cout << str[i] << endl;",
" for (int i = 0; i <= 13; i++) cout << str[7] + aDoubleQuot + str[i] + aDoubleQuot + ',' << endl;",
" for (int i = 8; i <= 13; i++) cout << str[i] << endl;",
" return 0",
"}"
};
for (int i = 0; i <= 6;i++) cout << str[i] << endl;
for (int i = 0; i <= 13; i++) cout << str[7] + aDoubleQuot + str[i] + aDoubleQuot + ',' << endl;
for (int i = 8; i <= 13; i++) cout << str[i] << endl;
return 0;
}
想办法用最简短的语句实现Quine确实很考验思维和代码能力,也有一定难度,这里只是随便玩玩没有深入研究,比起那些写成一行或者使用宏定义的精简代码,这个版本可以说是最浅显最易理解的写法了。
值得注意的大概以下几点:
· 用char 34来代替'\"'
,endl代替\n,规避了转义字符的绕来绕去,为了打印出\,则需要\\,如此死循环肯定行不通,其他处理方式又需要额外逻辑判断。
· 将程序分为2部分,一部分负责记录代码,另一部分运行时打印。