I'm making a program that takes a standard text file and converts it into an HTML document. for the most part it works fine and I am just improving it's functionality now, but there is this strange thing that happens when I save the title to a string/char arrray to print later. 6 characters, randomly determined by some magical force every time I run the binary get added to the start of the string "title".
Here is the code I believe is the problem:
char title[128]; /*handles the title of the webpage*/
printf("Creating file %s", htmlname);
/*begins creating the first open-tags, from the doctype to <title>*/
puttag(html, "!DOCTYPE html");
puttag(html, "html");
puttag(html, "head");
puttag(html, "title");
/*reads the start of txt until it finds a newline; prints all characters it finds along the way*/
ch = fgetc(txt);
while (ch != '\n')
{
fprintf(html, "%c", ch);
addchar(title, ch);
ch = fgetc(txt);
}
/*closes <title> and <head>; opens <body>*/
closetag(html, "title");
closetag(html, "head");
puttag(html, "body");
/*puts string "title" in <h1> tags*/
puttag(html, "h1");
fprintf(html, "%s", title);
closetag(html, "h1");
/*FUNCTION DEFINITIONS*/
/*puts string "tag" in <> brackets and prints it into fp*/
void puttag(FILE *fp, char *tag)
{
fprintf(fp, "\n<%s>\n", tag);
}
/*puts string "tag in </> brackets and prints it into fp"*/
void closetag(FILE *fp, char *tag)
{
fprintf(fp, "\n</%s>\n", tag);
}
/*adds character "ch" to string "str"*/
void addchar(char *str, char ch)
{
int i = strlen(str);
str[i] = ch;
str[i + 1] = '\0';
}
and the output created by this piece of the code looks like this:
<!DOCTYPE html>
<html>
<head>
<title>
This is the title
</title>
</head>
<body>
<h1>
p6+��This is the title
</h1>
I am new to C and have absolutely no idea why this is happening, so I do apologise if this is too much or too little sample to determine the problem.
One thing I have noticed is that this problem only appeared as I was adding later parts of the code to the program, even though I am absolutely sure that they have nothing to do with ths issue. This is the only place that this string is used, and strings are not used at all after this code(apart from when I check to see how long the string is, when It returns 23, 6 characters longer than the actual length of the title). Another thing is, sometimes, possibly the first time that it gets compiled after a restart(?), the program returns the correct string. I haven't investigated this much.
If anyone knows what is going on, help would be greatly appreciated.