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 は文字列です。文字列、または少なくとも または と比較する必要がありconst char *ますconst char[]

この式lastTwoChars == 41は、lastTwoChars を 41--an と比較しintます。これは、文字列に対して定義された動作ではありません。

代わりに、41 を引用符で囲んでconst char[](具体的にはconst char[3]):

 if (lastTwoChars == "41")

コードでこれを数回行っているようです。

于 2013-04-23T18:59:33.420 に答える
3

おそらく、エラーは、文字列を数値と比較できないことを訴えています。これらは 2 つの異なるタイプであり、一部の言語とは異なり、それらの間に魔法の変換 (または比較) はありません。

別の文字列と比較したい:

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の定義された動作に反します。それをstringまたはchar*と比較する必要があります。

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

"41"この場合はconst char*になり、文字列またはchar*と比較できます。

于 2013-04-23T19:12:34.560 に答える