不务正业系列:初识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 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部分,一部分负责记录代码,另一部分运行时打印。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值