【问题标题】:Why is strcmp not returning 0 in this context?为什么 strcmp 在这种情况下不返回 0?
【发布时间】:2012-04-13 16:06:30
【问题描述】:

所以我正在从文件中一个一个地读取字符:

char temp[3];

temp[0] = nextchar;
printf("%c",temp[0]); //prints %

temp[1] = nextchar = fgetc(srcptr);
printf("%c",temp[1]); //prints 2

temp[2] = nextchar = fgetc(srcptr);
printf("%c",temp[2]); //prints 0

if(strcmp(temp, "%20") == 0) { printf("%s","blahblah"); }

理想情况下,这应该在最后打印“blahblah”。然而,事实并非如此。那么为什么 strcmp 返回 0,更重要的是:我该如何解决它?

【问题讨论】:

    标签: c strcmp


    【解决方案1】:

    你需要 null 终止 temp。

    编辑

    将char temp[3]; 更改为char temp[4]; temp[3] = 0;

    【讨论】:

      【解决方案2】:

      改用memcmp,因为strcmp 期望两个字符串都以'\0' 结尾(而temp 不是):

      if(memcmp(temp, "%20", sizeof(temp)) == 0) { printf("%s","blahblah"); }
      

      【讨论】:

        【解决方案3】:

        字符串是一个字符数组,以 '\0' 字符结尾。由于您的 tmp 数组可以容纳三个字符,并且它们都不是终止空字符,因此 strcmp (和任何其他字符串函数)会认为它会继续,读取分配空间后的内存,直到遇到空字符(或崩溃为读取有限的内存空间很累)。

        字符串“%20”实际上是字符:'%', '2', '0', '\0'

        所以修复它的最简单方法是将tmp 声明为大一个并将'\0'分配给最后一个元素:

        char tmp[4];
        ...
        tmp[3] = '\0';
        

        【讨论】:

          猜你喜欢
          • 2016-03-02
          • 2014-09-12
          • 2018-04-26
          • 2018-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多