简体   繁体   English

为什么我的运算子==不匹配

[英]Why does my operator== have no match

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!";
}

The above code gives me the following compile error: 上面的代码给了我以下编译错误:

error: no match for 'operator==' (operand types are 'std::string {aka std::basic_string}' and 'char')| 错误:与“ operator ==”不匹配(操作数类型为“ std :: string {aka std :: basic_string}”和“ char”)|

I don't know what the issue is. 我不知道问题是什么。

Could anyone give some advice on this? 有人可以对此提供一些建议吗? Thanks! 谢谢!

'y' is a character literal, and there is no conversion operator comparing std::string with a character. 'y'是字符文字,并且没有将std::string与字符进行比较的转换运算符。 There is an operator for comparing to other std::string objects, or to C-style strings, so using "y" and "n" instead will work. 有一个运算符可与其他std::string对象进行比较,或与C风格的字符串进行比较,因此可以使用"y""n"代替。

'n' is a char , response is a string. 'n'是一个charresponse是一个字符串。 Strings are arrays of characters. 字符串是字符数组。 I don't know how you're assigning a value to response , but if you're pulling from an istream, you're going to have to sanitize it before you can use it. 我不知道如何为response分配值,但是如果要从istream中提取值,则必须先对其进行清理,然后才能使用它。 You will then either have to use either 然后,您将要么必须使用

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

to compare the entire string to a string of length 1 比较整个字符串和长度为1的字符串

or 要么

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

to compare one character in the string. 比较字符串中的一个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM