【问题标题】:cant compare string returning function with a string无法将字符串返回函数与字符串进行比较
【发布时间】:2021-09-04 00:55:24
【问题描述】:

我已经创建了这个函数,它是一个类的成员函数,这个函数中使用的 get 函数是另一个返回字符串的类的函数,但是当我将它与字符串进行比较时,它不起作用,即 if - 语句未执行

void printcarwheelstate() {

  if(w.getwheelstate()=="Moving")
  {
      setcartomoving();

  cout<<"Wheel 1 is "<<arr[0]<<endl;
    cout<<"Wheel 2 is "<<arr[1]<<endl;
     cout<<"Wheel 3 is "<<arr[2]<<endl;
      cout<<"Wheel 4 is "<<arr[3]<<endl;
  }
  else
  {
      setcartostopped();
      cout<<"Wheel 1 is "<<arr[0]<<endl;
    cout<<"Wheel 2 is "<<arr[1]<<endl;
     cout<<"Wheel 3 is "<<arr[2]<<endl;
      cout<<"Wheel 4 is "<<arr[3]<<endl;
  }
}

【问题讨论】:

  • 显示您的完整代码。
  • 如果车轮状态为“正在移动”,则代码开始移动购物车,这似乎很奇怪。
  • 我的猜测:getwheelstate 不会返回正确的 std::string 而是 char const *char *,也就是 C 风格的字符串。然后你将比较指针,而不是字符串内容。我们需要一个minimal reproducible example 来确定。
  • 请告诉我们getwheelstate() 是如何实现的,因为该功能与问题相关。我们不关心cout的8行。
  • @churill class wheel { 私有:字符串状态;公共:无效setwheelstate(字符串s){状态=s; } string getwheelstate() { 返回状态; } };

标签: c++ function class


【解决方案1】:

尝试打印 w.getwheelstate() 以查看它返回的内容。 你检查过大写和小写字母吗?因为它们在比较字符串时存在差异,并且它们的ascii代码不同。

你也可以试试这个:

tmp = w.getwheelstate().compare("Moving")
if (tmp == 0)
{
//body
}

【讨论】:

    【解决方案2】:

    我已经为它编写了代码。它 100% 功能齐全。

    代码在这里

        #include<iostream>
    
    #include<string.h>
    using namespace std;
    class State {
        
        string state ="";
        public:
         void setwheelstate( string state){
            this->state  =state;
            
        }
            string getwheelstate(){
           return   this->state ;
            
        }
        
    };
    
    int main ()
    {
        int arr[5]= {1,3,4,5,6};
        State state;
        state.setwheelstate("Moving");// you can also use this "if" statement
       // if ( state.getwheelstate().compare("Moving") == 0); 
        if(state.getwheelstate()=="Moving")
      {
         // setcartomoving();
      cout<<" IF Statement"<<endl;
      cout<<"Wheel 1 is "<<arr[0]<<endl;
        cout<<"Wheel 2 is "<<arr[1]<<endl;
         cout<<"Wheel 3 is "<<arr[2]<<endl;
          cout<<"Wheel 4 is "<<arr[3]<<endl;
      }
      else
      {
         // setcartostopped();
         
      cout<<" Else Statement"<<endl;
          cout<<"Wheel 1 is "<<arr[0]<<endl;
        cout<<"Wheel 2 is "<<arr[1]<<endl;
         cout<<"Wheel 3 is "<<arr[2]<<endl;
          cout<<"Wheel 4 is "<<arr[3]<<endl;
      }
        
        
    }
    

    这段代码的输出是:

    希望它对你有用。如果您仍然遇到问题,则存在逻辑错误而不是语法

    【讨论】: