【发布时间】:2018-11-25 23:59:42
【问题描述】:
我有这个代码。代码的目的是打印<img> 之前的所有内容以及</img> 之后的所有内容。不应打印<img> 和</img> 之间的所有内容。但是,我有 2 个问题。
- 代码正在 windows 上编译(gcc 编译器),但是当我运行它时,它只是说“程序停止工作”?
- 代码正在打印所有内容。它甚至打印
<img>,</img>以及介于两者之间的所有内容。
我的#includes:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
代码:
void replacer_and_print(FILE *fp) {
char* line;
size_t len;
ssize_t read;
bool found_tag = false;
int line_storer;
char* before_tag;
char* after_tag;
while ((read = getline(&line, &len, fp)) != -1) {
if (
((before_tag = strstr(line, "<img>")) != NULL) &&
((after_tag = strstr(line, "</img>")) != NULL)
) {
line_storer = before_tag - line;
printf("%.*s", line_storer, line);
printf("The Image use to be here\n");
line_storer = after_tag - line + strlen("</img>");
printf("%s", line + line_storer);
} else if ((before_tag = strstr(line, "<img>")) != NULL) {
line_storer = before_tag - line;
printf("%.*s", line_storer, line);
found_tag = true;
} else if((after_tag = strstr(line, "</img>")) != NULL) {
found_tag = false;
line_storer = after_tag - line + strlen("</img>");
printf("%s", line + line_storer);
} else if(!found_tag) {
printf("%s", line);
}
}
fclose(fp);
}
test.html:
<b>This is a test page</b>
<div class=back1>Some more text here for more testing!!!!</div>
<img>www.website.com/image.png</img>
<i>More words</i>
<u><i><b>TESTING 123</u></i></b>
输出:
<b>This is a test page</b>
<div class=back1>Some more text here for more testing!!!!</div>
The Image use to be here
<i>More words</i>
<u><i><b>TESTING 123</u></i></b>
假设:
There will only be one <img>
There will only be one </img>. The </img> tag will always be after the <img>
【问题讨论】:
-
欢迎来到 StackOverflow!在大多数情况下,这是一篇不错的第一篇文章;但是,您应该在帖子中包含您不会帮助解决的任何错误。您声明代码无法在 Windows 上编译,能否包含编译器错误?
-
@c1moore 完全没有错误。它编译得很好。但是,当我运行它时,它就会停止工作,
-
那你为什么在你的帖子中包含#1?
-
@c1moore 措辞错误,抱歉。编辑了帖子
-
提示:当输出有问题时,用
<>等标记围绕字符串 输出,并用\n结束每个输出。它更好地暴露了过多的空白、换行、回车问题。例如。printf("%.*s", line_storer, line);-->printf("<%.*s>\n", line_storer, line);