1

我正在尝试解析网页并使用 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) 中。处理包含字符串 < dt > 的行的部分如下。

   } else if (strstr(tmp,"<dt>")) {
       strcpy(tmp,strstr(tmp,"<dt>")+4);
       strcpy(strstr(tmp,"</dt>")," \0");
       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: 

我没有得到 Moonphase:,而是得到 Mo>\nphase:,而不是得到 Past 24h-Snow:,而是得到 Paw:24-hr Snow:。奇怪的是,只有这些特定的字符串才会发生这种情况。我不能将字符串上 strstr 的结果复制到字符串本身吗?

strcpy(tmp,strstr(tmp,"")+4);

这是违规行吗?我在其余代码中使用相同的方法没有问题。如果我使用中间变量(buff)来存储 strstr 搜索的结果

} else if (strstr(tmp,"<dt>")) {
    strcpy(buff,strstr(tmp,"<dt>")+4);
    strcpy(strstr(buff,"</dt>")," \0");
    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)='\0';
       if (strstr(tmp,"Chance of"))
               strcpy(tmp,"Chance of precipitation: ");
       fwrite(tmp,1,strlen(tmp),file_tod);

合法吗?

4

1 回答 1

2

strcpy()未定义源字符串和目标字符串重叠时等函数的行为。

如果您必须在原地移动内存(字符串),请确保您知道字符串的长度并使用memmove(); 当字符串重叠时,这可以保证工作。

于 2012-05-27T15:27:29.480 回答