【问题标题】:C programming language :if statements are not working correctly with characters [duplicate]C编程语言:if语句无法正确处理字符[重复]
【发布时间】:2015-05-01 03:14:23
【问题描述】:

我正试图让这个程序说好,但它说好 虽然我使变量值与 if 测试值相同

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char history[200];
    history == "NY school";

    if(history == "NY school")
    {
        printf("good");
    }
    else{printf("okay");}
    return 0;
}

【问题讨论】:

  • 使用strcpystrcmp分配和比较字符串
  • 您正在比较指针,因此出现错误。还有man 3 strcmp.

标签: c if-statement chars


【解决方案1】:

你需要使用strcmp函数

  if (strcmp(history ,"NY school") == 0) ....

否则你是在比较指针

加变

  history == "NY school";

使用strcpy

【讨论】:

    【解决方案2】:

    这应该适合你:

    #include <stdio.h>
    #include <string.h>
            //^^^^^^^^ Don't forget to include this library for the 2 functions
    
    int main() {  
    
        char history[200];
        strcpy(history, "NY school");
      //^^^^^^^Copies the string into the variable
        if(strcmp(history, "NY school") == 0) {
         //^^^^^^ Checks that they aren't different
            printf("good");
        } else {
            printf("okay");
        }
    
        return 0;
    
    }
    

    有关strcpy() 的更多信息,请参阅:http://www.cplusplus.com/reference/cstring/strcpy/

    有关strcmp() 的更多信息,请参阅:http://www.cplusplus.com/reference/cstring/strcmp/

    【讨论】:

    • 谢谢你帮了我很多:)
    • @talalalsharaa 不客气!祝你有美好的一天:D(顺便说一句:你可以接受如何帮助你最大并解决你的问题的答案!(meta.stackexchange.com/q/5234))
    • 只做char history[200] = "NY school"; 也可以。
    【解决方案3】:

    不能分配字符串(这将使用单个=,而不是您的代码中的==)。在标准头 &lt;string.h&gt; 中查找 strcpy() 函数。

    此外,不能使用关系运算符(==!= 等)比较字符串(或任何数组)——此类比较比较指针(数组第一个元素的地址)不能字符串的内容。要比较字符串,请使用strcmp() 函数,同样在&lt;string.h&gt; 中。

    【讨论】:

      【解决方案4】:

      通过一些实现定义的优化器运气,这也可能起作用:

      #include <stdio.h>
      
      int main(void)
      {
        char * history = "NY school";
      
        if (history == "NY school") /* line 7 */
        {
          printf("good");
        }
        else
        {
          printf("okay");
        }
      
        return 0;
      }
      

      至少在 gcc (Debian 4.7.2-5) 4.7.2 编译时它可以工作,顺便说一句没有优化。

      上面显示的代码打印:

      good
      

      在编译期间它会触发警告(对于第 7 行):

       warning: comparison with string literal results in unspecified behavior [-Waddress]
      

      【讨论】:

      • 正如其他 cmets 和回复所指出的,字符串无法使用 == 运算符进行比较。必须使用 strcmp() 函数(在标准头文件 中声明)。
      • @Rob:我展示的代码不比较“字符串”,而是比较它们的指针。
      • 没错。问题是无法保证这些指针是否相等。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多