validating a phone number

hello everyone, I am trying to validate a phone number so the program will check if the user inputted this format (123-45-6789). The phone number is inputted as a string character and I am trying to use a for loop to check each individual character. Within this same function, I am also trying to have it loop until the user inputs the correct phone number. Here is what I have so far:

This functions purpose is when the user selects 'A'(add) from the menu and then takes you to other functions.
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  //*************************************************************
void pickingOptions(char selection, ifstream& inRentalData, apartmentInfo addApartment[], int& cnt)
{
	// variable
	int num;
    string phoneNumber;
    float rentAmount;
    float status;
    char yesNo;
    bool inserted = false;
	
	switch (selection)
	{
		case 'S':
			// Display all the apartment information on file
			displayRental(addApartment, cnt);
			break;
		case 'A':
			//loop to keep adding apartments until user is done
			cout << "---- The following 3 questions are for adding an apartment ----" << endl << endl;
			while(!inserted)
			{
				// phone number prompt and validation
				phonePrompt (PHONE_PROMPT, phoneNumber, cnt, inserted);
				phoneValidation (phoneNumber);
				addApartment[cnt].phoneNum = phoneNumber;
				
				// rent amount prompt and validation
				rentAndStatusPrompt (RENT_PROMPT, rentAmount, cnt, inserted);
				rentValidation (rentAmount);
				addApartment[cnt].rent = rentAmount;
				// rental status prompt and validation
				rentAndStatusPrompt (STATUS_PROMPT, status, cnt, inserted);
				statusValidation (status);
				addApartment[cnt].rentalStatus = status;	
			
				// prompt user to continue or not 
	 			cout << "---- Do you wish to add more apartments to the list (Y/N)? ----" <<endl;
	 			cin >> yesNo;
	 			yesNo = toupper(yesNo);
	 			if (yesNo == 'Y')
	 				inserted = false;
	 			else 
	 				inserted = true;
	 			// add counter to array
	 			cnt++;
	 		}
			break;
		case 'D':
			//deleteApartment();
			break;				
	}
	return;
}    
//********************************************************** 

This function prompts the user for a phone number and returns the value via references parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void phonePrompt (string prompt, string& promptAnwser, int& listSize, bool& test)
{                           
  if (listSize == MAX_ARRAY)     // check to see if Array is full
  {
  	cout << "ERROR - No more apartments can be added to list!" << endl;
  	test = true;
  } 
  else 							// proceed if array is NOT full
  {  	 
  	 cout << prompt << endl;
  	 cin >> promptAnwser; 	 
  }  // end else
     
  return;
}
//********************************************************** 

This function is supposed to validate the phone number and continue to loop until the user gets the correct format. This is where I am stuck.
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
//***************************************************************************

void phoneValidation (string& phone)
{
	//variables
	bool invalidFormat = false;
	
	//will loop as long as format is incorrect (bool = true)
	do
	{
		char dash = '-';
		
		for (int i= 0; i < phone.length()-1; i++)
    	{
        	if (i == 3 || i == 6)
            	phone[i] == dash ;
        	else
        	{
        		isalpha(phone[i]);
        		invalidFormat = true;
			}
    	}
    	// if total characters within the phone number does not equall 12 
    	if (phone.length()!= 12)
   			invalidFormat = true;
   		
   		// if bool = true, than re-prompt for new phone number
   		if (!invalidFormat)
   		{
   			cout << "ERROR! Invalid phone number (Format: ###-###-####). Please re-enter your phone number: " << endl;
   			cin >> phone;
		}
	}while (!invalidFormat);
    	
    return;
} 

I am fairly new to this. Any help would be greatly appreciated. Thanks to everyone for your help.
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
#include <iostream>
#include <string>
#include <cctype>

bool valid_phone( std::string str )
{
    static const std::string pattern = "(ddd-dd-dddd)" ; // use <regex> ?

    if( str.size() != pattern.size() ) return false ;

    for( std::size_t i = 0 ; i < str.size() ; ++i )
    {
        if( pattern[i] == 'd' ) // digit expected
        {
            if( !std::isdigit( str[i] ) ) return false ;
        }
        else if( pattern[i] != str[i] ) return false ;
    }

    return true ;
}

int main()
{
    std::string phone ;

    while( std::cout << "phone number? " && std::cin >> phone && !valid_phone(phone) )
        std::cout << "invalid phone number '" << phone << "'\n" ;

    std::cout << "the phone number is: '" << phone << "'\n" ;
}
Last edited on
Thank you for your response. Where does this test if I have a dash('-')? Does the regex test for a dash? We haven't covered regex yet, so I don't think I'm supposed to use that. Thanks again JLBorges.
> Does the regex test for a dash?

There is no regex here. pattern is a simple std::string


> Where does this test if I have a dash('-')?

Line 17. For instance, when i == 4, if( pattern[4] != str[4] ) return false ;
I see how it all works. Thanks for clearing that up, JLBorges.
So I changed a few things around, so the function will re-prompt for another number if it is wrong. This actually works. Thank you for pointing me in the right direction.

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
39
//***************************************************************************
void phoneValidation (string& phone)
{
	//variables
	bool invalidFormat = false;
	
	while (!invalidFormat)
	{
		// initial loop to check the users phone number. One character at a time
	    for( int i = 0 ; i < phone.size() ; ++i )
	    {
	        if( PATTERN[i] == 'd' ) 			// digit expected
	        {
	            if( !isdigit( phone[i] ) ) 		//If there is not a digit return false
					invalidFormat = false ;
				else							
					invalidFormat = true ;
	        }
	        else if( PATTERN[i] != phone[i] ) 	//if the const PATTERN (ddd-ddd-dddd) doesn't = the phone number return false
				invalidFormat = false ;
			else 
				invalidFormat = true ;
	    }
	    if( phone.size() != PATTERN.size() ) 	// if the number of characters in the phone number doesn't = the pattern size return false
			invalidFormat = false ;
		else
			invalidFormat = true ;
		
        if (!invalidFormat)						// if false than re-prompt question
		{
			cout << endl;
			cout << "ERROR! Invalid phone number(format: ###-###-####). Re-enter phone number: " << endl;
			cin  >> phone;
		}
		else	
			invalidFormat = true;	
	}
    return;
}
Topic archived. No new replies allowed.