tags:

views:

75

answers:

1

Hi Friends,

I need a c,c++ code for validating a Phone Number(8 Digits- Starting with 2) and Mobile Number(10 Digits- Starts with 9).

Also it should not allow to enter any space, special charcter, as well as charcters.

Here user can enter either phone number or mobile number.

Plese Help in this,

Thanks,

A: 

Here's the code:

bool is_valid_number(const std::string& number)
{
    static const std::string AllowedChars = "0123456789";
    for(auto numberChar = number.begin(); 
        numberChar != number.end(); ++numberChar)

        if(AllowedChars.end() == std::find(
            AllowedChars.begin(), AllowedChars.end(), *numberChar))
        {
            return false;
        }

    return true;
}

// client code
std::string  number = "091283019823";

bool isMobileNumber = is_valid_number(number) 
                      && number.size() == 10 
                      && number[0] == '9';
bool isLandLineNumber = false; // left as an exercise to the reader ;)

The function is_valid_number could be improved to work on iterators instead of strings, or written as a functor on a single char and used with std::find_if to write the whole thing as a one-liner.

utnapistim
-1 For posting code in response to homework question.
qrdl
I didn't realize it was homework - I thought he needed it for some project :(
utnapistim