user6687683
user6687683

Reputation:

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.

Upvotes: 2

Views: 1266

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57688

You can use std::ostringstream, such as:

std::string example = "10";
unsigned int value;
std::istringstream text_stream(example);
text_stream >> value;

You may want to use the dec modifier to handle any preceding zeros:
text_stream >> dec >> value;

I haven't tried it though. The issue is based on C++ numeric constants that begin with 0 are treated as octal (base 8).

Edit 1: Example program

#include <string>
#include <sstream>
#include <iostream>

int main(void)
{
    std::string example = "010";
    unsigned int value;
    std::istringstream text_stream(example);
    text_stream >> value;
    if (value == 10)
    {
        std::cout << "Coversion correct\n";
    }
    else
    {
        std::cout << "Invalid conversion.\n";
    }

    return 0;
}

Upvotes: 0

Ohashi
Ohashi

Reputation: 396

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 https://stackoverflow.com/a/8889045/5118228 explains how to roll your own tester function.

Upvotes: 1

Related Questions