How to Validate a phone number in C++?

In this tutorial, we are going to learn how to Validate a phone number in C++. As you know area codes and phone numbers length are different for different regions, so we will try to Validate a number whose area code length is 3 and the length of number is 8. So let us move to our code implementation.

Validate a phone number in C++

C++ source code:

// Validate a phone number in C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
  string areacode;
  string phone_number;
  cout<<"Enter your area code: ";
  cin>>areacode;
  int flag1=0;
  cout<<"Validating your area code.....\n";
  
  // Checking if area code is correct
  for(int i=0;i<areacode.length();i++)
  {
    if(areacode[i]-48>=0 && areacode[i]-48<=9)
    {
      flag1=1;
      continue;
    }
    else
    {
      flag1=0;
      break;
    }
  }
  if(flag1==1 && areacode.length()==3)
  {
    cout<<"You have entered right area code.\n";
  }
  else if(flag1==0)
  {
    cout<<"You have entered wrong area code.\n";
  }
  else if(areacode.length()!=3)
  {
    cout<<"You have entered wrong area code.\n";
  }
  cout<<"Enter your phone number: ";
  cin>>phone_number;
  int flag2=0;
  cout<<"Validating your phone number.....\n";
  
  // Checking if number is correct
  for(int i=0;i<phone_number.length();i++)
  {
    if(phone_number[i]-48>=0 && phone_number[i]-48<=9)
    {
      flag2=1;
      continue;
    }
    else
    {
      flag2=0;
      break;
    }
  }
  if(flag2==1 && phone_number.length()==8)
  {
    cout<<"You have entered right number.\n";
  }
  else if(flag2==0)
  {
    cout<<"You have entered wrong number.\n";
  }
  else if(phone_number.length()!=8)
  {
    cout<<"You have entered wrong number.\n";
  }
  return 0;
}

Output:

Enter your area code: 011
Validating your area code.....
You have entered right area code.
Enter your phone number: 24242424
Validating your phone number.....
You have entered right number.

--------------------------------
Process exited after 5.362 seconds with return value 0
Press any key to continue . . .

Explanation of Code:

In the code, we are checking if all entered characters are digits or not if they are digits and their length are as equal as they are mentioned correct output is printed. We are converting all character values into integers by using ASCII values. After converting if they lie between o and 9 inclusive we will print right output.

One can use own length of area codes and numbers according to their region.

If you have any query regarding the code do let me know in the comments section.

You can also learn,

Validating phone numbers in JavaScript



How to send SMS in PHP?

Leave a Reply

Your email address will not be published. Required fields are marked *