【问题标题】:Why does my operator== have no match为什么我的 operator== 没有匹配
【发布时间】:2023-03-30 12:38:01
【问题描述】:
if(response=='y'){
    cout << "great. file saved, please send the file to me and you'll receive the package information and status.";
}
else if(response=='n'){
    cout << "exiting. please do it again correctly, thanks!";
}

上面的代码给了我以下编译错误:

错误:'operator==' 不匹配(操作数类型是 'std::string {aka std::basic_string}' 和 'char')|

我不知道是什么问题。

有人可以就此提供一些建议吗?谢谢!

【问题讨论】:

  • 使用"y" 而不是'y'

标签: c++


【解决方案1】:

'n' 是一个charresponse 是一个字符串。字符串是字符数组。我不知道您如何为response 分配值,但如果您从 istream 中提取,则必须先对其进行消毒,然后才能使用它。然后,您将不得不使用任何一个

if(response=="y") //note the double quotes

将整个字符串与长度为 1 的字符串进行比较

if(response[0]=='y')

比较字符串中的一个字符。

【讨论】:

  • [0] 是做什么的?
  • response[n] 从字符串中获取第 n 个char。索引 0 是第一个 char
【解决方案2】:

'y' 是一个字符文字,并且没有将std::string 与字符进行比较的转换运算符。有一个运算符用于与其他 std::string 对象或 C 样式字符串进行比较,因此使用 "y""n" 代替将起作用。

【讨论】:

  • 它通过 cin tho 从用户那里获取 y 或 n(是或否)?
  • @exceem 'y'"y" 不是一回事。
  • @exceem std::cin 返回一个字符串,它返回用户输入的任何内容,而不仅仅是"y" 或`"n"。它将存储它看到的整个字符串,直到遇到空格。
猜你喜欢
  • 2019-03-18
  • 2016-07-30
  • 1970-01-01
  • 2010-11-09
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多