将s.at(i)与一个角色进行比较?

时间:2017-09-15 19:06:22

标签: c++ string templates

我收到错误,C ++禁止将指针与字符进行比较

无论在哪里我将s.at(i)与任何东西进行比较,都会出现某种错误的错误。

 string s;
        cout<<"Enter the expression";
        getline(cin,s);
        int i;
        for(i=0;i<s.length();i++)
          {
              if(s.at(i)=="("||s.at(i)=="["||s.at(i)=="{")
                push(s.at(i));
          }
          for(i=0;i<s.length();i++)
          {
              if(s.at(i)=="]"||s.at(i)==")"||s.at(i)=="}")
              {
                  x=pop();
                  if (s.at(i)==x)
                    continue;
                  else
                  {enter code here
                      cout<<"\nInvalid expression";
                      return 0;
                  }
              }
          }

2 个答案:

答案 0 :(得分:2)

考虑s.at(i)=="("

文字 "("实际上是const char[2]类型((的一个元素,NUL-terimator的另一个元素),在某些情况下将衰减到const char*指针,例如使用==时的情况。

s.at(i)返回单个char类型,该类型与const char*指针进行比较。您有用的编译器会警告您此错误。

解决方案很简单:改为使用'(',这是一个char字面值。您可以将charchar进行比较。

答案 1 :(得分:1)

您将字符包含在双引号")"中,使其成为字符串或char *。它们应该是单引号,例如')',因此它们会成为char