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 wer
#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;
}
lastTwoChars is a string. You must compare it to a string, or at least a const char *
or const char[]
.
The expression lastTwoChars == 41
compares lastTwoChars to 41--an int
. This is not defined behavior for a string.
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.
Presumably, the error is complaining that you can't compare a string to a number. They are two different types, and unlike some languages there is no magic conversion (or comparison) between them.
You want to compare with another string:
if (lastTwoChars == "25")
// ^ ^
lastTwoChars
is a string, you are comparing it with an int in these statements :
if (lastTwoChars == 41)
{
cout << "Red";
}
if (lastTwoChars == 25)
{
cout << "Black";
}
if (lastTwoChars == 30)
{
cout << "Green";
}
This is against the defined behaviour for string. You have to compare it to a string or char*.
if (lastTwoChars == "41")
{
}
cout << "Red";
.
.
.
Now "41"
is a const char* in this case and it can be compared with a string or a char*.