I need some direction on how to validate a phone number that is entered by the user. My instructor says I cannot use brute force (checking each individual character) but rather use the string's array feature and use loops to check each index of the string. It must confirm that the first 3 characters are digits, a dash, 3 more digits, a dash, and then 4 more digits. I cannot quite seem to wrap my head around how to do this through loops, I can only do it by checking each individual string index.
What I think he means is I can't just do something like "is string a digit? "is string a digit? is string a digit? is string a dash? etc.." but use loops to increment the index and continue checking as long as the number keeps abiding by the phone number format specified.
His specific instructions:
NOTES: Error checking of the characters in the phone numbers should be done using a loop or loops, not using brute force to check each individual character. Remember that you can access individual characters as if the string was an array of characters.
For example: inputPhoneNum could be used to access the first character in the phone number input by the user.
HINT: For each index, determine whether the character should be a digit or dash. Then use a character function from the cctype library to check for digits if it should be a digit, or simply test if the character is a dash.
I would recommend using a regular expression. Example in pseudo code:
1 2 3 4 5 6 7 8 9 10 11 12 13
// first sub-match is first 3 digits
// second sub-match is second 3 digits
// third sub-match is last 4 digits
// see if it matches
string str_num = phone_num_matches + phone_num_matches + phone_num_matches;
int phone_num = boost::lexical_cast<int>(str_num);
// It must confirm that the first 3 characters are digits, a dash, 3 more digits,
// a dash, and then 4 more digits.
// is the character c valid for position pos?
bool is_valid_char( char c, std::string::size_type pos )
constchar dash = '-' ;
if( pos == 3 || pos == 6 ) // positions where dash is expected
return c == dash ;
else // positions where a digit is expected
return std::isdigit(c) ;
// is this a valid phone number?
bool is_phone_number( const std::string& candidate )
const std::string::size_type EXPECTED_SIZE = 3+1+3+1+4 ;
if( candidate.size() != EXPECTED_SIZE ) returnfalse ;
for( std::size_t i = 0 ; i < EXPECTED_SIZE ; ++i ) // for each position in the string
if( !is_valid_char( candidate[i], i ) ) returnfalse ;