set up a boolean, eg
bool isvalid{true}; //until proven otherwise, the value is valid..
then loop until happy:
do
isvalid = true; //reset it each loop!
read a number
test it.
for each test, you want something like
isvalid = isvalid && testresult;
while(!isvalid); //loop until you get a valid number
if you want to get fancy you can skip tests once isvalid is false.
#include <iostream>
#include <fstream>
#include <string>
// #include<bits/stdc++.h>
usingnamespace std;
bool isValid(const string& phone)
{
const string areaCode[] = { "520", "620","405", "550", "650" };
if (phone.length() != 10)
{
cout << "Invalid phone number ," << endl;
returnfalse;
}
// only focus first tree numbers to identify it is in right area code
string area_C = phone.substr(0, 3);
// Use the find function to check if the code is valid
if (find(begin(areaCode), end(areaCode), area_C) == end(areaCode))
{
cout << "( !!ERROR!! ,Wrong area code or Invalid phone Number ! ) \n ";
returnfalse;
}
// Passed all tests
cout << "The phone number is valid" << endl;
returntrue;
}
int main()
{
string phoneNumber;
//Print the Company name
cout << "********************************************************************\n";
cout << " X Y Z Regular (wired) Telephone Service \n";
cout << "*********************************************************************\n";
cout << "Enter the your phone number: ";
while (1) // Loop forever if not valid
{
// Let user enter their phone number
cin >> phoneNumber;
if (isValid(phoneNumber))
break; // break out of loop
// We've already displayed what is wrong
cout << "Please re-enter your phone number" << endl;
}
// Got a valid phone number, exit the program
return 0;
}