Originally Posted by
omaralqady
I am a beginner in C, and I was trying to make a program which reads an "int x" and creates a number of strings equivalent to the "x", and also name the variables accordingly in series such as:string1,string2,... . I tried many ways to do it by myself and I also looked for it in many tutorials but I couldn't figure it out. So please help me if you can
Please also tell me if I haven't done my homework and where I should look because I did look for it and search for it but with no luck so far.
Well actually it is much simpler to avoid using arrays, by writting a progra mthat writes a program tailor made to the user needs :P.
However my solution assumes the user has configured his path to be able to invoke the c compiler and immediately enter the desired strings. Notice the care taken to properly indent the resulting program.
Code:
#include <stdio.h>
int main()
{
int nsub, i;
FILE *f;
printf("Enter the number of subjects:");
scanf("%d", &nsub);
if( (f = fopen("prog.c","w")) == NULL)
return printf("Error opening file.\n");
fputs("#include <stdio.h>\n\nint main()\n{", f);
fprintf(f, "\tint i;\n");
for(i=0; i<nsub; i++)
fprintf(f, "\tchar string%d[256];\n", i);
fprintf(f, "\n");
for(i=0; i<nsub; i++)
{
fprintf(f, "\tprintf(\"Please enter string%d:\");\n", i);
fprintf(f, "\tfgets(string%d, 256, stdin);\n", i);
}
fprintf(f, "\n\treturn 0;\n}\n");
fclose(f);
system("gcc -o prog prog.c");
system("./prog");
return 0;
}
This is just a joke actually, and not to be taken seriously.