首页 > 解决方案 > C++ 电话号码验证

问题描述

我正在尝试验证用户输入的电话号码。该号码必须输入为 xxxxxxxxxx 而不是 xxx-xxx-xxxx 或其他任何内容。如果输入的内容包含不是数字的任何内容,则应将其视为无效,并且用户必须重新输入数字。到目前为止,如果在开始时输入了无效输入,我的程序可以正常工作,但是,我想检查输入的任何内容是否不是数字。例如,klsj456778、--87389474 和 23708-- 都应被视为无效输入。使用我现在拥有的程序,只有前两个被认为是无效的,需要用户重新输入号码。此外,我必须将 phone 变量保留为 int 数据类型,这就是为什么我不只是将其更改为字符串的原因。是否有可能做到这一点?我一直在寻找不同的资源,但无法找到答案。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    long long phone;
    string check;
    bool status;
    string fail = "";
    //validate input
    do
    {
        cout << "Enter phone number(without - or letters): ";
        cin>>phone;

        //in order to type check
        if (cin.fail())
        {
            //you have to clear these before continuing
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Invalid Input" << endl;
        }
        else
        {

            check = to_string(phone);

            if (check.length() == 10)
            {
                if (check.substr(0, 3) == "405" || check.substr(0, 3) == "520" || check.substr(0, 3) == "550")
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                break;
            }
            else
            {
                status = false;
            }

            break;
        }

    } while (true);
    if (status == true)
    {
        cout << "\nPhone number: " << phone << endl;
        cout << "Verification Status: Valid";
    }
    else
    {
        cout << "Phone number: " << phone << endl;
        cout << "Verification Status: Invalid";
    }
}

标签: c++

解决方案


推荐阅读