Displaying Source Code

I have to write a programme that displays its source code without using file handling. How can I do this ?
Have a look here: http://www.cprogramming.com/challenges/self_print.html if you're really stuck
It's in C but it's still useful.
Basically you put the whole program in a string array in your .cpp file and then have your program cout the contents of the array.
1
2
3
4
5
6
7
8
#include <stdio.h>
char *program = "#include <stdio.h>%cchar *program = %c%s%c;%cint main()%c{%c
printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c    return 0;%c}%c";
int main()
{
        printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);
        return 0;
}

what's happening here ?
#include <stdio.h>
This is the C I/O Header.
C++ Equivalent
#include <iostream>

the program C String is storing a recursive copy of the program. Think of it like you wrote your program on a piece of paper and then used that piece of paper in another program
 
printf()
if the cout for C
translated to C++, the program stands
1
2
3
4
5
#include <iostream>
using namespace std;
char **program = "#include <iostream>%cchar *program = %c%s%c;%cint main()%c{%c
printf(program, 10, 34, program, 34, 10, 10, 10, 10, 10, 10);%c    return 0;%c}%c";
int main()

Well it's a bit difficult for me as i am not very fluent in C, maybe someone who knows C can help you?
I'll post an example later. It's getting late here

The two key tricks here are using a string with an embedded %s specifier to allow the string to contain itself when printed, and to use the %c format specifier to allow printing out special characters like newlines, which could not otherwise be embedded in the output string.

Last edited on
Topic archived. No new replies allowed.