简单字符串代码中不匹配"operator ==" [英] No match for 'operator==' in a simple string code

查看:94
本文介绍了简单字符串代码中不匹配"operator =="的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个简单的代码并遇到问题,我不确定该如何处理.我尝试通过搜索对其进行搜索,但发现没有什么帮助很大,每个人的回答都超出了我的脑袋.有人请像个小孩一样解释这个,哈哈.谢谢.

Writing a simple code and ran into a problem I'm not sure how to deal with. I tried looking into it with a search but nothing I found was much help and everyone's answers were a little above my head. Someone please explain this like you would to a small child, haha. Thanks.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string invCode = "";
    string lastTwoChars = "";

    cout << "Use this program to determine color of furniture.";
    cout << "Enter five-character inventory code: ";
    cin >> invCode;

    if (invCode.length() == 5)
    {
        lastTwoChars = invCode.substr(3,2);
         if (lastTwoChars == 41)
         { 
              cout << "Red";
              }
         if (lastTwoChars == 25)
         { 
              cout << "Black";
              }
         if (lastTwoChars == 30)
         { 
              cout << "Green";
              }
    }
    else
         cout << "Invalid inventory code." << endl;

    system("pause"); 
    return 0;
}

推荐答案

lastTwoChars是一个字符串.您必须将其与字符串或至少为const char *const char[]的字符串进行比较.

lastTwoChars is a string. You must compare it to a string, or at least a const char * or const char[].

表达式lastTwoChars == 41将lastTwoChars与41-一个int进行比较.这不是字符串的定义行为.

The expression lastTwoChars == 41 compares lastTwoChars to 41--an int. This is not defined behavior for a string.

取而代之的是将41放在引号中,使其成为const char[](特别是const char[3]):

Instead, put 41 in quotes to make it a const char[] (specifically const char[3]):

 if (lastTwoChars == "41")

您似乎在代码中多次执行了此操作.

It looks like you do this several times in your code.

这篇关于简单字符串代码中不匹配"operator =="的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆