c++ - 验证电话号码和手机号码

标签 c++ c

我需要一个 c、c++ 代码来验证电话号码(8 位数字 - 以 2 开头)和手机号码(10 位数字 - 以 9 开​​头)。

也不允许输入任何空格、特殊字符以及字符。

在这里用户可以输入电话号码或手机号码。

请帮忙,

谢谢,

最佳答案

代码如下:

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 ;)

函数 is_valid_number 可以改进以在迭代器而不是字符串上工作,或者在单个 char 上写为仿函数并与 std::find_if 一起使用以将整个事物写成一行.

关于c++ - 验证电话号码和手机号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3108454/

相关文章:

c++ - 位字段结构分配意外行为

c++ - 隐式转换类模板

c - 提取交错 float 据

c - 我究竟如何产生这个输出?

c - 我不断收到“第一个函数中的线程 1 EXC_BAD_ACCESS 断点

c++ - 单一来源项目结构的缺点是什么?

基类中的 C++ 方法

c - 我的 C 程序中存在内存泄漏

c - 对短代码进行可靠的性能测量

c++ - 为代码块安装 MinGW 的 gdb.exe