gpt4 book ai didi

c++ - 字符串类中指针和整数的比较 - C++

转载 作者:行者123 更新时间:2023-12-01 15:13:21 24 4
gpt4 key购买 nike

我是 C++ 新手。

string str = "WWWHBBB";
if(str[mid] == "H" && str[0] != "W") return; // corrected after comments for second operand

上面带有 if 的行条件给了我一个错误。

Comparison between pointer and integer ('std::__1::basic_string, std::__1::allocator >::value_type' (aka 'char') and 'const char *')



我已经在互联网上搜索了足够多的内容,知道数组样式访问在字符串中很好。错误基本上是指出关于指针和整数的比较。真的吗?我以为我在比较字符 H到字符串中的另一个字符 str .

我试过如果 str[mid]真的返回一个我应该做的迭代器 *str[mid] .不!也没有用。

最佳答案

在 if 语句的表达式中

 if(str[mid] == "H" && str[mid] != "W") return;

类型为 const char[2] 的字符串文字 "H"和 "W"被隐式转换为指向它们的第一个字符的指针 const char * .

因此,您尝试比较表达式 str[mid] 返回的字符用指针。

而不是字符串文字,您需要使用字 rune 字来比较字符
 if(str[mid] == 'H' && str[mid] != 'W') return;

你也可以这样写
 if(str[mid] == *"H" && str[mid] != *"W") return;

或者
 if(str[mid] == "H"[0] && str[mid] != "W"[0]) return;

取消引用指针,但这会令人困惑

注意如果 str[mid] == 'H'那么第二个操作数将始终为真。所以写就够了
 if( str[mid] == 'H' ) return;

关于c++ - 字符串类中指针和整数的比较 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60956326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com