加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 取消引用字符串迭代器产生int

发布时间:2020-12-16 03:34:48 所属栏目:百科 来源:网络整理
导读:我收到这个错误 comparison between pointer and integer ('int' and 'const char *') 对于以下代码 #include iostream#include sstream#include stringusing namespace std;int main(){ std::string s("test string"); for(auto i = s.begin(); i != s.end(
我收到这个错误
comparison between pointer and integer ('int' and 'const char *')

对于以下代码

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    std::string s("test string");
    for(auto i = s.begin(); i != s.end(); ++i)
    {
        cout << ((*i) != "s") << endl;
    }
}

为什么解除引用字符串迭代器会产生一个int而不是std :: string?

解决方法

实际上,它不会产生一个int,它会产生一个char(因为字符串迭代器迭代字符串中的字符).由于!=的另一个操作数不是char(它是一个const char [2]),标准的促销和转换将应用于参数:

>通过整体推广将char提升为int
> const char [2]通过数组到指针的转换转换为const char *,

这是你到达编译器抱怨的int和const char *操作数的方法.

您应该将解除引用的迭代器与字符进行比较,而不是与字符串进行比较:

cout << ((*i) != 's') << endl;

“”包含一个字符串文字(类型const char [N]),”包含一个字符文字(char类型).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读