PixelFallHD PixelFallHD - 2 months ago 5x
C++ Question

How to convert string to int in c++?

I am creating a phone registration program to check if a phone number entered is valid. I have tried searching google numerous times and have figured out how to check the phone numbers length and whether it starts with "04"; it seem as though there is nothing to check whether a string can be converted to an unsigned integer without an error though. My current code is:

bool Is_Valid(string phone) {
if (phone.length() == 10 && phone.substr(0,2) == "04") {
return 1;
} else {
return 0;

The desired result would be that if the user entered in a string that is ten characters long and starts with "04" but the string has a letter in it, the function would return false. Likewise if the character entered in a string that was ten characters long and it started with "04" as well as having no letters, it would return true. Thank You.


You may find difficulties if you convert such strings to ints because those have a leading zero, which will be dropped on conversion.

I'd suggest std::all_of and ::isdigit from the standard library;

if (phone.length() == 10 && phone.substr(0, 2) == "04"
    && std::all_of(phone.begin(), phone.end(), ::isdigit)) // added

This would work. Remember to include <algorithm> and <cctype>.

Please note that it requires C++11 (or newer), which is activated by -std=c++11 if you are using gcc. If C++11 is unavailable, this answer http://stackoverflow.com/a/8889045/5118228 explains how to roll your own tester function.