0

编写一个简单的代码并遇到了一个我不知道如何处理的问题。我尝试通过搜索对其进行调查,但没有发现任何帮助,而且每个人的答案都超出了我的想象。请有人像对小孩一样解释这个,哈哈。谢谢。

#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;
}
4

4 回答 4

6

lastTwoChars 是一个字符串。您必须将其与字符串进行比较,或者至少与 a const char *or进行比较const char[]

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

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

 if (lastTwoChars == "41")

看起来您在代码中多次执行此操作。

于 2013-04-23T18:59:33.420 回答
3

据推测,错误是抱怨您无法将字符串与数字进行比较。它们是两种不同的类型,与某些语言不同,它们之间没有神奇的转换(或比较)。

您想与另一个字符串进行比较:

if (lastTwoChars == "25")
//                  ^  ^
于 2013-04-23T18:59:10.560 回答
1

lastTwoChars是一个字符串,你在这些语句中将它与一个int进行比较:

         if (lastTwoChars == 41)
         { 
              cout << "Red";
         }
         if (lastTwoChars == 25)
         { 
              cout << "Black";
         }
         if (lastTwoChars == 30)
         { 
              cout << "Green";
         }

这违反了string的定义行为。您必须将其与字符串char*进行比较。

         if (lastTwoChars == "41")
         { 
         }
              cout << "Red";
         .
         .
         .

在这种情况下, Now"41"是一个const char*,它可以与一个字符串或一个char*进行比较。

于 2013-04-23T19:12:34.560 回答
0
 #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 == "fourty five") // you declared lastTwoChars as string therefore you have to compare letters not integers which are numbers.
          { 
               cout << "Red";
          }
     if (lastTwoChars == "twenty five") //same
     { 
          cout << "Black";
          }
     if (lastTwoChars == "thirty") // same
     { 
          cout << "Green";
          }
}
else
     cout << "Invalid inventory code." << endl;

cin.get(); // better than system("pause");
return 0;
}
于 2013-04-24T00:06:01.540 回答