我想用 C 语言将以下 html 打印到控制台。但是,我的代码中有一个错误让我很困惑,我不知道怎么会发生这种情况?错误是它再次打印最后一个字符数组。
示例输出:
<html>
<body>
<p>Hey There!</p>
<p>You can search for things on the internet at:
<ul>
<li> <a href="http://www.google.com">Google</a></li>
<li> <a href="http://www.bing.com">Bing</a></li>
</ul>
</p>
</body>
</html>
My output:
<html>
<body>
<p>Hey There!</p>
<p>You can search for things on the internet at:
<ul>
<li> <a href="http://www.google.com">Google</a></li>
following line is incorrect. It prints the above line again.
<li> <a href="http://www.bing.com" href="http://www.google.com">Bing</a></li>
</ul>
</p>
</body>
</html>
我的代码:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void open_tag(char tag[], char attribute[]){
char str1[100];
char str2[100];
char str3[100];
//The bug happens here.The attribute[] is incorrect.
strcpy (str1,tag);
strncat (str1, attribute, 100);
strcpy (str2,"<");
strcpy (str3,">");
strncat (str2, str1, 100);
strncat (str2, str3, 50);
printf ("%s",str2);
}
void close_tag(char tag[]){
char str1[20];
char str2[20];
char str3[20];
strcpy (str1,tag);
strcpy (str2,"</");
strcpy (str3,">");
strncat (str2, str1, 6);
strncat (str2, str3, 6);
printf ("%s",str2);
}
int main(int argc, char *argv[])
{
open_tag("html", "");
printf("\n");
open_tag("body", "");
printf("\n");
open_tag("p", "");
printf("Hey There!");
close_tag("p");
printf("\n");
open_tag("p", "");
printf("You can search for things on the internet at:");
printf("\n");
open_tag("ul", "");
printf("\n");
open_tag("li", "");
char arr2[] = {' ','h','r','e','f','=','\"','h','t','t','p',':','/','/','w','w','w','.','g','o','o','g','l','e','.','c','o','m','\"'};
open_tag("a", arr2);
printf("Google");
close_tag("a");
close_tag("li");
printf("\n");
open_tag("li", "");
char arr1[] = {' ','h','r','e','f','=','\"','h','t','t','p',':','/','/','w','w','w','.','b','i','n','g','.','c','o','m',' ','\"'};
open_tag("a", arr1);
printf("Bing");
close_tag("a");
close_tag("li");
printf("\n");
close_tag("ul");
printf("\n");
close_tag("p");
printf("\n");
close_tag("body");
printf("\n");
close_tag("html");
printf("\n");
return 0;
}
最佳答案
当您创建并传递attribute
时,它不是 null 终止的。然后强制它复制 100 个字符(使用 strcat
),然后在其末尾附加字符( <
和 >
)
我建议你在 arr1
上放置一个终结符字符和arr2
在传递字符串之前(通过添加 '\0'
字符)。
那就不要使用strncat(..., 100)
,只需使用简单的 strcat()
.
关于c - C 中 char 数组的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805969/