【问题标题】:function to check whether a string is an int not working检查字符串是否为 int 的函数不起作用
【发布时间】:2016-08-12 05:40:14
【问题描述】:

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

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

【问题讨论】:

  • 没有错误,它只是在我输入十个字符长并且以“04”和“08”开头的内容时进行身份验证。即使字符串中有字母

标签: c++ login codeblocks registration


【解决方案1】:

做两个括号。 &amp;&amp;|| 之前评估,因此如果 phone.length() == 10 &amp;&amp; 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;
    }
}

像 cmets 中提到的rakete1111 函数可以简化为:

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

【讨论】:

  • 谢谢@Rakete1111
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2014-04-30
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2012-06-17
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多