不务正业系列:初识Quine之C++一种简单实现

不务正业系列:初识Quine之C++一种简单实现偶然听说了 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

大家好,我是讯享网,很高兴认识大家。

偶然听说了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部分,一部分负责记录代码,另一部分运行时打印。

小讯
上一篇 2025-02-22 17:51
下一篇 2025-04-09 20:56

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/39503.html