函数检查字符串是否为int型

function to check whether a string is an int not working

本文关键字:int 是否 检查 字符串 函数      更新时间:2023-10-16

我一直在创建一个程序来检查电话号码是否有效,如果电话号码以"04"开头但有十个字母长,我的程序将返回true。下面是检查字符串是否为unsigned int的函数代码:

bool Is_Int(string phone) {
    if (all_of(phone.begin(), phone.end(), ::isdigit)) {
        return true;
    } else {
        return false;
    }
}

下面是检查电话号码是否有效的代码:

bool Is_Valid(string phone) {
    if (phone.length() == 10 && phone.substr(0,2) == "04" || phone.substr(0,2) == "08" && Is_Int(phone)) {
        return true;
    } else {
        return false;
    }
}

,这是主程序代码:

int main()
{
    cout << "Enter Phone Number: ";
    string PhoneNumber;
    getline(cin, PhoneNumber);
    if (Is_Valid(PhoneNumber)) {
        cout << "authenticated" << endl;
    }
    return 0;
}

错误是,如果我输入"04abcdefgh",它将打印authenticated

画两个括号。&&||之前求值,因此如果phone.length() == 10 && phone.substr(0,2) == "04"为真,则if为真

bool Is_Valid(string phone) {
    if (phone.length() == 10 && (phone.substr(0,2) == "04" || phone.substr(0,2) == "08") && Is_Int(phone)) {
        return true;
    } else {
        return false;
    }
}

与注释中提到的rakete1111一样,函数可以简化为:

bool Is_Valid(string phone) {
    return (phone.length() == 10 && (phone.substr(0,2) == "04" || phone.substr(0,2) == "08") && Is_Int(phone));
}

也许,正则表达式更清楚?

bool Is_Valid(string phone) {
  return QRegularExpression(R"(^0(4|8)d{8}$)").match(phone).hasMatch();
}
  1. 字符必须为0
  2. 字符可能是4或8
  3. 尾部8位