Only allowing certain input pattern

I have a program that I need to write for my computer coding class that involves only allowing a sequence of either the letter a or b, followed by any two numbers, and if this is not followed it just result in a error message and loop back to the question asking for their area code. I've been having difficulties with the entirety of our string unit and just can't seem to wrap my head around the ideas, and would really appreciate if someone here could show me how to do this, thanks!

Currently this is all I have done, the program doesn't require much it's just that pesky input restriction that I can't get.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{


	double shipCharge = 0.0;
	string regionCode;	
	bool correctInput;

	cout << "Enter a region code(enter -1 to stop):  ";
	cin >> regionCode;

	while (regionCode.length != 3  )



	return 0;
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
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <cctype>

bool valid_region_code( std::string str )
{
    return str.size() == 3 && // length == 3
           ( str[0] == 'a' || str[0] == 'b' ) && // first character is either a or b
           std::isdigit( str[1] ) && // second character is a digit
           std::isdigit( str[2] ) ; // third character is a digit
}

// return false if -1 is entered to signal end of input
bool get_region_code( std::string& str )
{
    std::cout << "enter region code (enter -1 to stop): " ;
    std::cin >> str ;

    if( str == "-1" ) return false ;

    if( valid_region_code(str) ) return true ;

    std::cout << "invalid region code " << str << ". try again\n" ;
    return get_region_code(str) ; // try again
}

int main()
{
    std::string rc ;
    while( get_region_code(rc) )
    {
        std::cout << "region code is: " << rc << '\n' ;

        // do something with the region code
    }

    std::cout << "\nbye!\n" ;
}
Last edited on
Thanks, this works perfectly, and I can now use this as reference when coding in the future, I appreciate it!
Topic archived. No new replies allowed.