在简单的字符串代码中不匹配'operator =='

use*_*308 0 c++ string operator-keyword

编写一个简单的代码并遇到问题我不知道如何处理.我试着通过搜索来调查它,但我找不到任何帮助,每个人的答案都有点高于我的头脑.请有人像小孩子一样解释这个,哈哈.谢谢.

#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;
}
Run Code Online (Sandbox Code Playgroud)

App*_*ish 6

lastTwoChars是一个字符串.你必须将它与一个字符串,或至少一个const char *const char[].

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

相反,将41放在引号中以使其成为const char[](具体const char[3]):

 if (lastTwoChars == "41")
Run Code Online (Sandbox Code Playgroud)

看起来你在代码中多次这样做了.