18

我遇到了一个在这个站点上打印自己的程序,即它打印程序代码。

程序代码为:

#include <stdio.h>
char *program = "#include <stdio.h>%cchar *program = %c%s%c;%cint main()%c{%cprintf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c    return 0;%c}%c";
//what is this line doing, what is the use of %c and %s and what properties of %c and %s are being used here?
int main()
{
        printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);
        //what is this print function doing, and how?
        return 0;
}

给出的解释是:

这里的两个关键技巧是使用带有嵌入式 %s 说明符的字符串以允许字符串在打印时包含自身,以及使用 %c 格式说明符来允许打印出特殊字符,例如换行符,否则这些字符无法嵌入到输出字符串。

我不明白程序是如何工作的。我已经提到了我需要解释的行,它们是如何工作的以及它们在做什么。请解释。

4

4 回答 4

8
char *program = "#include <stdio.h>%cchar *program = %c%s%c;%cint main()%c{%cprintf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c    return 0;%c}%c";

有一个 char 指针名称“program”,用于存储字符串,%c 和 %s 分别是 char 和字符串参数的格式说明符。

printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);

printf 函数正在将输出打印到控制台,这里 10 是 NEWLINE 的 ASCII 码,34 是“ printf 参数正在执行的操作

  • 程序,传递要打印的字符串
  • 10 ,为第一个 %c 传递 10 个 ASCII 码(将转换为字符换行符)
  • 程序,再次将相同的字符串传递给程序中的 %s 以再次打印相同的字符串
  • 34 ,为第二个 %c 传递 34 ASCII 码(将转换为字符双引号)
  • 10 ,为第 3 个 %c 传递 10 ASCII 码(将转换为字符换行符)
  • 10 ,为第 4 个 %c 传递 10 ASCII 码(将转换为字符换行符)
  • 10 ,为第 5 个 %c 传递 10 ASCII 码(将转换为字符换行符)
  • 10 ,为第 6 个 %c 传递 10 ASCII 码(将转换为字符换行符)
  • 10 ,为第 7 个 %c 传递 10 ASCII 码(将转换为字符换行符)
  • 10 ,为第 8 个 %c 传递 10 ASCII 码(将转换为字符换行符)
于 2011-10-07T17:56:02.073 回答
2

Printf 打印作为第一个参数给出的字符串(在本例中是 in 中的字符串*program)替换您有 %s 或 %c 的其他参数

%s 表示争论是一个字符串,%c 是一个字符。

正如注释所说,它使用 %s 在程序字符串中打印程序字符串的副本 - 因此制作副本,并使用 %c 打印字符 10(新行)和 34"

于 2011-10-07T17:46:04.670 回答
0

For a better understanding, the variable program could have been written like this:

"#include <stdio.h>\nchar *program = \"%s\";\nint main()\n..."

The idea is, that you run the program, compile it's output, run that program and so on. But this can only been done with %c values 10 for linefeed and 34 for double quote.

于 2011-10-07T18:06:47.713 回答
-4

这可以使用文件处理来完成。以任何名称保存程序并将该名称放在 fopen 命令中的打开目录中。就像我的程序的名字是hello.cpp。

这是以下程序

#include <stdio.h>
#include <iostream>
int main()
{
    FILE *fp;   
    fp=fopen("hello.cpp","r");
    char ch;
    while((ch=fgetc(fp))!=EOF)
    {
       printf("%c",ch);
     }
}
于 2016-09-19T22:01:35.173 回答