Search the string of numbers to check if it contains any letters

In my function isValid I need to check the string phoneNumber and make sure it only contains the digits 0-9. If it does contain a letter I must set status=3. With my current code phoneNumber.find_first_not_of("02345789",0) the status is ALWAYS set to 3 even if I enter the correct values. Any guidance would be great, thanks.

int isValid ( string phoneNumber)
{
int status;
if (phoneNumber.length() != 8 && phoneNumber.length() != 11 )
{

status= 1;
}
else if ( phoneNumber.at(0) != '1')
{
status = 2;
}
else if ( phoneNumber.find_first_not_of("02345789",0))
{
status = 3;
}
else
{
status = 0;
}
return status;
}
You can use std::all_of with std::isdigit to check if the string only contains numbers.
http://www.cplusplus.com/reference/algorithm/all_of/
http://www.cplusplus.com/reference/cctype/isdigit/
I believe I can only use #include<iostream>, string, and iomanip in my program. My apologies for not stating that above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>

enum status
{
    OK = 0,
    BAD_LENGTH = 1,
    DOES_NOT_BEGIN_WITH_1 = 2,
    CONTAINS_NON_DIGIT = 3
};

const std::size_t SMALL_SZ = 8 ;
const std::size_t LARGE_SZ = 11 ;

status is_valid( std::string phone_number )
{
    // check for valid length
    if( phone_number.size() != SMALL_SZ && phone_number.size() != LARGE_SZ )
        return BAD_LENGTH ;

    // check that phone number begins with '1' (why?)
    else if( phone_number.front() != '1' ) return DOES_NOT_BEGIN_WITH_1 ;

    // check presence of non-digits
    // note: find_first_not_of returns std::string::npos if not found
    else if( phone_number.find_first_not_of("0123456789") != std::string::npos )
        return CONTAINS_NON_DIGIT ;

    else return OK ;
}
Perfect!!! thank you so much! It worked perfectly just by adding
else if ( phoneNumber.find_first_not_of("0123456789") != std::string::npos )
{
status=3;
}
looks like i was missing the != std::string::npos
Any idea what that does? I know that the phoneNumber.find_first_not_of("0123456789")
searches the phoneNumber string for any occurrence that is not one of those digits so logically I thought it would work.
> I know that the phoneNumber.find_first_not_of("0123456789")
> searches the phoneNumber string for any occurrence that is not one of those digits

If an occurrence is found, it returns the position at which it was found: a value in [ 0, size()-1 ]
If not, it returns std::string::npos.

If phone_number.find_first_not_of("0123456789") returns a value other than std::string::npos,
it means that a character that is not one of the decimal digits was found.
Topic archived. No new replies allowed.