PixelFallHD PixelFallHD - 3 months ago 18
C++ Question

function to check whether a string is an int not working

I have been creating a program to check whether a phone number is valid and my program is returning true if the phone number starts with "04" but is ten letters long. Here is the code for the function checking if the string is an unsigned int:

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


Here is the code checking if the phone number is valid:

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


and this is the main program code:

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


The error is that if i type "04abcdefgh" it will print authenticated

Answer

Make two brackets. The && is evaluated before the || and therefore the if is true if phone.length() == 10 && phone.substr(0,2) == "04" is true

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

Like rakete1111 mentioned in the comments the function can be reduced to:

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