### String Troubles

We are posed with this problem.

An office furniture company sells furniture in three colors: red, black and green. Every item in their inventory system has a 5-character code.
a. The first three characters are always used to represent the furniture type. If the first three characters are T47 then the furniture is a table, if the first three characters are C47 then the item is a chair
b. The last two characters are always used to represent color. If an item is red, the last two characters are 41. If an item is black, the last two characters are 25. If an item is green, the last two characters are 30.
c. Ask the user to enter a 5-character code. Use the first three characters to determine the furniture type and the last 2 characters to determine the color. Display the type (chair or table) and the color in the console window (Red, Black or Green).
d. Generate an error message (Invalid inventory code) if:
a. If the inventory code is not exactly 5 characters long, or
b. if the last two characters are neither 41, 25 nor 30 or
c. the first three characters are not T47 or C47

[Hint: Use the substr function to extract the last two characters of the string and see whether the extracted substring is 41, 25 or 30) same with the first three characters ]

I am lost. I have tried several things where I have either gotten an error or it will compile, but give me nothing or the wrong thing. Here is what I have.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546`` ``````#include #include using namespace std; int main() { string inventCode = ""; cout << "Enter 5 character inventory code: "; cin >> inventCode; if (inventCode.length() == 5) { if (inventCode.substr(0, 3) == "C47" && inventCode.substr(4, 2) == "41") { cout << "Chair - Red" << endl; } else if (inventCode.substr(0, 3) == "C47" && inventCode.substr(4, 2) == "30") { cout << "Chair - Green" << endl; } else if (inventCode.substr(0, 3) == "C47" && inventCode.substr(4, 2) == "25") { cout << "Chair - Black" << endl; } else if (inventCode.substr(0, 3) == "T47" && inventCode.substr(4, 2) == "41") { cout << "Table - Red" << endl; } else if (inventCode.substr(0, 3) == "T47" && inventCode.substr(4, 2) == "30") { cout << "Table - Green" << endl; } else if (inventCode.substr(0, 3) == "T47" && inventCode.substr(4, 2) == "25") { cout << "Table - Black" << endl; } } else cout << "Invalid inventory code " << endl; system("pause"); return 0; }``````
I have started over completely from this. But any guidance on this would be much appreciated.
On a string of length 5, substr(4,2) is only the last character. Indexing begins at 0, not 1.

To get a string that consists of the last two characters of any string (assuming a length of 2 or greater):

`s.substr(s.length()-2);`
Last edited on
Topic archived. No new replies allowed.