string.find or string.substr?

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace 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;
}
Last edited on
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.
Last edited on
What about string::operator[] ??

I don't see a need for string::find() here. And there's info (plus an example) for string::substr() here:

string::substr
http://www.cplusplus.com/reference/string/string/substr/

Andy
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const std::string::size_type LEN = 7;
const char *colors = "bgrw";
string item;

while ( true )
{
	cout << "Enter item number (seven characters, the fourth should be a b,g,r,or w): ";
	cin >> item;

	if ( item.length() == LEN && strchr( colors, item[3] ) )
	{
		auto IsDigit = []( char c ) { return ( isdigit( c ) ); };
		if ( all_of( item.begin(), next( item.begin(), LEN / 2 ), IsDigit ) &&
		     all_of( next( item.begin(), LEN / 2 + 1 ), item.end(), IsDigit ) )
		{
			break;
		}
	} 


	cout << item << " - not a valid item number" << endl;
}
Last edited on
Many ways to do this

Here is one;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string item;

	cout << "Enter item number (seven characters, the fourth should be a b,g,r,or w): ";
	cin >> item;

   item.erase (0,3); // Erase first 3 chars
   item.erase (1,10); // Erase chars 2-10
//   cout << item << endl;
   
   if (item=="b")
   {cout << "Blue" << endl;}
   else if (item=="g")
   {cout << "Green" << endl;}
   else
   {cout << "not blue or green" << endl;}
   
return 0;
}
Topic archived. No new replies allowed.