函数检查字符串是否为int型
function to check whether a string is an int not working
我一直在创建一个程序来检查电话号码是否有效,如果电话号码以"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();
}
- 字符必须为0
- 字符可能是4或8
- 尾部8位
相关文章:
- 是否可以从int转换为enum类类型
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 是否可以保证按字节的零 int 是零的表示形式?
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 将uint8_t转换为已签名的 int 是否至少有时不正确?
- 判断 int 是否在 C++ 中赋值的任何优雅方法
- 从std::round转换为int是否安全
- 有没有办法检查int是否不等于数组中的所有值?(C )
- "!" "== 0"是否检查 int 是否是 0 的好做法?
- 从函数返回向量<向量<int>>是否会调用 C++11 中的任何移动构造函数
- 确定 int 是否包含特定数字的函数出现问题
- int 是否有运算符==
- 确定 int 是否不为 0,没有 if 语句
- 本地引用int是否有任何好处
- 在C++中,函数定义的int a[]和int*a是否相同
- 在C++中递增未初始化的 int 是否安全
- 将string映射到int是否可能比使用hashmap更快?
- Int a=1, a || 1是否为常量表达式
- ' int a = 0, b = a '是否有未定义的行为?
- 将本机方法定义为公共本机synchronized int doSum(int a, int b)是否正确?