【问题标题】:ISO C++ forbids comparison between pointer and integer [-fpermissive] [c++]ISO C++ 禁止指针和整数之间的比较 [-fpermissive] [c++]
【发布时间】:2020-01-17 12:42:13
【问题描述】:

ISO C++ 禁止指针和整数比较 [-fpermissive]

      if(S[i] == "#")
                 ^~~ 
#include <iostream>
using namespace std;

int main() {
    string S = "a#b#";
    for( int i=0; i< S.length(); i++){
        if(S[i] == "#")
            //do somethng
    }
    return 0;
}

在谷歌上搜索此错误时,我发现了一种解决方法,方法是使用 if( &amp;S[i] == "#") 中的“&”,它工作正常。有人可以告诉我为什么这样做,这里发生了什么?

【问题讨论】:

标签: c++ string


【解决方案1】:

您正在迭代字符,但您将字符 (char) 与 (const char *) 进行比较。

您应该将其与字符“#”进行比较。

#include <iostream>
using namespace std;

int main() {
    string S = "a#b#";
    for( int i=0; i< S.length(); i++){
        if(S[i] == '#') // here <--
            //do somethng
    }
    return 0;
}

您可以将其简化为基于范围的 for 循环:

#include <iostream>
using namespace std;

int main() {
    string S = "a#b#";
    for(char character : S){
        if(character == '#')
            //do somethng
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    &S[i] == "#" 与 s[i]=='#' 不同,因为前者比较指针地址,结果为假。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多