Issues using substr to access characters

In this code I am supposed to enter a 5 character inventory code. The inventory code has a color associated with it and I am supposed to be able to use substr
to access the last two characters in the inventory code. If the inventory code entered does not match it is an "Invalid Inventory Code". If I enter one of the correct codes it tells me the color associated with it but also Invalid inventory code. Not sure if I am missing something or if part of my code might be out of order. Any ideas?

[code]

#include <iostream>
#include <string>

using namespace std;

int main()
{
const string INVALID_MSG = "Invalid Inventory Code";
string inventCode = "";

cout << "Enter five-character Inventory code (-1 to end): ";
cin >> inventCode;

while (inventCode != "-1")
{
if (inventCode.length()!= 5)
{
cout << INVALID_MSG << endl;
}
{
if (inventCode.substr(4, 2)!= "41" || inventCode.substr(4, 2)!= "30" || inventCode.substr(4,2)!="25")
{
cout<<INVALID_MSG<<endl;
}
if (inventCode=="T4741")
{
cout<<"Red"<<endl;
}

if (inventCode=="T4725")
{
cout<<"Black"<<endl;
}
if (inventCode=="T4730")
{
cout<<"Green"<<endl;
}
}

cout << "Enter five-character Inventory code (-1 to end): ";
cin >> inventCode;

}
system("pause");
return 0;
}


[code]
Try this for your if statement:

if (inventCode.length() < 5 || inventCode.length() > 5) {
cout << INVALID_MSG << endl;
}

else if (inventCode.substr(3,2 ) == "41") {
cout<<"Red"<<endl;
}


else if (inventCode.substr(3, 2) == "25") {
cout<<"Black"<<endl;
}

else if (inventCode.substr(3, 2) =="30") {
cout<<"Green"<<endl;
}

else{
cout << INVALID_MSG << endl;
}
Topic archived. No new replies allowed.