【问题标题】:if and char statementif 和 char 语句
【发布时间】:2016-07-14 18:30:27
【问题描述】:

你好,这不是我的全部代码,但我被困在这个地方,只有当用户输入“NewYork”这个词时我才需要打印信息,并且当我调试时,即使我输入“NewYork”这个词也不会打印任何内容.那么任何人都可以告诉可能是什么问题吗?谢谢

int main(){

    Panel *panelptr;
    int count,len,wid;
    double heg;
    char locat[30];

    cout<<"how many panels do you need to create ? "<<endl;
    cin>>count;
    panelptr = new Panel[count];
    assert(panelptr!=0);



    for(int i=0; i< count; i++){
        cout << "Enter the length: ";
        cin >>len;
        cout << "Enter the width: ";
        cin >> wid;
        cout << "Enter the height: ";
        cin >> heg;
        cout<<"Enter the location: ";
        cin >>locat;
        panelptr[i].setPanel(len,wid,heg,locat);

        if(locat == "NewYork")
            panelptr->print();

    }


    delete [] panelptr;
    system("pause");
    return 0;
}

【问题讨论】:

  • 您正在比较 char* 的指针值,而不是实际内容。尝试使用 std::string 而不是 char[]
  • 这条语句if(locat == "NewYork")实际上比较了两个永远不会相同的char*指针。
  • 无法使用 == 运算符比较数组。如果您坚持将locat 与字符串文字“NewYork”(使用数组表示)进行比较,请查找strcmp() 函数。更好的是,使用在标准头 &lt;string&gt; 中指定的 C++ 标准字符串类 (std::string) 而不是 char 的数组。

标签: c++ if-statement char


【解决方案1】:

您正在将 char 数组与字符串进行比较。使用strcmp() 进行比较:

if (strcmp(locat, "NewYork") == 0) {
}

【讨论】:

    【解决方案2】:

    你不能像你一样使用if(locat == "NewYork") 比较字符数组。你有两个选择:

    1) 使用strcmp()

    #include <cstring>
    int main()
    {
        char locat[30];
    
        if (strcmp(locat, "NewYork") == 0)
        {
            // Do what you like.
        }
    }
    

    2) 使用string

    #include <string>
    int main()
    {
        std::string locat;
    
        if (locat == "NewYork")
        {
            // Do what you like.
        }
    }
    

    【讨论】:

      【解决方案3】:

      对于字符串比较,您应该使用strcmp() 函数而不是==。您正在使用的只是比较两个char*,您不能指望它是相同的。
      所以,改变你的代码

      if(locat == "NewYork")
           panelptr->print();
      

      if(strcmp(locat, "NewYork") == 0)
           panelptr->print();
      

      strcmp() 定义在string.h 标头中,因此包含 #include&lt;string.h&gt; 在你的程序中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-24
        • 2022-01-01
        • 2015-03-12
        • 2014-10-15
        • 2013-07-12
        • 2016-03-02
        • 2016-02-29
        • 1970-01-01
        相关资源
        最近更新 更多