我正在尝试解析网页并从中提取天气信息C(受虐狂,我知道)。
在该页面中,有以下几行:
<dt>Chance of <span class='wx-firstletter'>rain</span>:</dt>
<dt>Wind:</dt>
<dt>Humidity:</dt>
<dt>UV Index:</dt>
<dt>Snowfall:</dt>
<dt>Sunrise:</dt>
<dt>Moonrise:</dt>
<dt>Moonphase:</dt>
<dt>Past 24-hr Precip:</dt>
<dt>Past 24-hr Snow:</dt>
<dt>Chance of <span class='wx-firstletter'>rain</span>:</dt>
<dt>Wind:</dt>
<dt>Humidity:</dt>
<dt>UV Index:</dt>
<dt>Snowfall:</dt>
<dt>Sunset:</dt>
<dt>Moonset:</dt>
<dt>Moonphase:</dt>
<dt>Past 24-hr Precip:</dt>
<dt>Past 24-hr Snow:</dt>
下载页面后,将其保存在文件中并在带有 fread 的数组中读取它,我使用循环逐行读取数组,将其保存到临时数组 (tmp) 中。处理包含字符串
} else if (strstr(tmp,"<dt>")) {
strcpy(tmp,strstr(tmp,"<dt>")+4);
strcpy(strstr(tmp,"</dt>")," ");
if (strstr(tmp,"Chance of"))
strcpy(tmp,"Chance of precipitation: ");
fwrite(tmp,1,strlen(tmp),file_tod);
} else if ....
一切都很顺利,除了月相和过去的24小时雪线。
Chance of precipitation:
Wind:
Humidity:
UV Index:
Snowfall:
Sunrise:
Moonrise:
Mo>
phase:
Past 24-hr Precip:
Paw: 24-hr Snow:
Chance of precipitation:
Wind:
Humidity:
UV Index:
Snowfall:
Sunset:
Moonset:
Mo>
phase:
Past 24-hr Precip:
Paw: 24-hr Snow:
我得到的不是月相:,而是Mo>相:而不是超过24小时雪:,我得到的是Paw:24小时雪:。奇怪的是,只有这些特定的字符串才会发生这种情况。我不能将字符串上的 strstr 结果复制到字符串本身吗?
strcpy(tmp,strstr(tmp,")+4);
这是冒犯的台词吗?我在其余代码中使用相同的方法,没有问题。如果我使用中间变量(buff)来存储strstr搜索的结果
} else if (strstr(tmp,"<dt>")) {
strcpy(buff,strstr(tmp,"<dt>")+4);
strcpy(strstr(buff,"</dt>")," ");
if (strstr(buff,"Chance of"))
strcpy(buff,"Chance of precipitation: ");
fwrite(tmp,1,strlen(buff),file_tod);
} else if ....
一切都很好。
感谢您的任何回答,如果很明显,请道歉。
编辑:想出了这个
} else if (strstr(tmp,"<dt>")) {
memmove(tmp,strstr(tmp,"<dt>")+4,strlen(tmp)-(strlen(strstr(tmp,"<dt>")+4)));
*(strstr(tmp,":")+1)=' ';
*(strstr(tmp,":")+2)=' ';
if (strstr(tmp,"Chance of"))
strcpy(tmp,"Chance of precipitation: ");
fwrite(tmp,1,strlen(tmp),file_tod);
合法吗?
源字符串和目标字符串重叠时,函数(如 strcpy()
)的行为是未定义的。
如果你必须让内存(字符串)原位移动,请确保你知道字符串的长度并使用memmove()
;当字符串重叠时,这保证可以工作。