I have to write a program that accepts a 7 character string of numbers and letters, such as 123b456. The fourth character has to be a b,g,r,or w. Then If the entered string is valid, It must print out "blue", "green", "red", or "white" corresponding to the fourth character in the string. How do I utilize the string.find or string.substr to read a string?
Sorry this is kind of confusing.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string item = "";
int num = 0;
int numPos;
cout << "Enter item number (seven characters, the fourth should be a b,g,r,or w): ";
cin >> item;
num = item.length();
numPos = item.find("b");
if (num != 7)
{cout << "Not a valid item number" << endl;}
system("pause");
return 0;
}
You could extract the 4th character like this: char ch = item[3]; // Assuming item length is at least 4
After that you could search for ch in a string which you define, containing the list of permitted characters. A not-found result means the input was invalid, while you could use a successful search result to allow the required output to be printed.
Or don't do any search. Just do a switch/case or series of if/elses to test the value of ch, and output the appropriate text.