Jake Wickham Jake Wickham - 3 months ago 12
C++ Question

How would i check if a phone number entered is a valid in c++?

I am creating a cruise management system in c++ and I need to check if a phone number entered during registration is valid (valid in Australia), basically if it starts with 04 and is 10 numbers long. I think there was a function for checking the length of a string but I'm unable to recall it. Perhaps something like:

int phonenumber;
cin >> phonenumber;
if (phonenumber.length() == 10 && FirstTwoLetters(phonenumber, 04) {
// rest of registering code
}


of course some of this code is made up but I'm sure you get the idea }Thank You

Answer

First of all, I suggest you to store the data information as a string, instead of integer. In order to do that, you need to include the library for string:

#include <string>

C++ String Reference STD

After you can use:

std::string phonenumber;

That's more efficient because an integer which starts with 0 is semantically equal to another integer with no 0.

E.g: 001234 == 1234

That's no true with strings.

Once you have stored the information in a string variable you have to check the structure in this way:

if ((phonenumber.length() == 10) && (phonenumber.substr(0, 2) == "04")) {
  std::cout << "Valid number\n";
}

Finally in order to make more robust your application, you need to check whether the string is composed by just digits. That's because the user could type:

04asdqwerty1

And the check will pass anyway.

The fastest way in my mind at this moment is to write a function:

bool check_all_digit(const std::string& str) {
  for(const auto& c : str) {
    if (c < 48 || c > 57) {
      return false;
    }
  }
  return true;
}

Note that this function uses a C++11 syntax.

That functions takes all characters of the string and check whether the ASCII code is not a digit.

ASCII code table

So the complete check will become:

if ((phonenumber.length() == 10) && (phonenumber.substr(0, 2) == "04") && (check_all_digit(phonenumber) == true)) {
  std::cout << "Valid number\n";
}
Comments