首页 > 解决方案 > ISO C++ 禁止指针和整数之间的比较 [-fpermissive] [c++]

问题描述

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( &S[i] == "#")它工作正常。有人可以告诉我为什么这有效,这里发生了什么?

标签: c++string

解决方案


您正在迭代字符,但您将字符 (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;
}

推荐阅读