Nadav
Nadav

Reputation: 2717

How to convert a digit in a string number to int

hello i have a problem i am trying to convert a string like "12314234" to int so i will get the first number in the string. from the example of string that is shown above i want to get '1' in int. i tried : string line = "12314234"; int command = line.at(0); but it puts inside command the ascii value of 1 and not the number 1. thanks in advance.

Upvotes: 1

Views: 354

Answers (5)

graham.reeds
graham.reeds

Reputation: 16476

Sorry to join this party late but what is wrong with:

int value;
std::string number = "12345";
std::istringstream iss(number);
iss >> value;

If you are passing hexadecimal around (and who isn't these days) then you can do:

int value;
std::string number = "0xff";
std::istringstream iss(number);
iss >> std::hex >> value;

It's C++ and has none of this hackish subtraction of ASCii stuff.

The boost::lexical_cast<>() way is nice and clean if you are using boost. If you can't guarantee the string being passed will be a number then you should catch the thrown error.

Upvotes: 1

fredoverflow
fredoverflow

Reputation: 263048

i am trying to convert a string like "12314234" to int

Boost has a library for this:

int i = boost::lexical_cast<int>(str);

Upvotes: 1

Timothy
Timothy

Reputation: 4650

The standard function to convert an ascii to a integral value is strtol (string to long) from stdlib (#include <cstdlib>). For information, see http://en.wikipedia.org/wiki/Strtol and then the link off that page entitled Using strtol correctly and portably. With strtol you can convert one numeric character, or a sequence of numeric characters, and they can be multiple bases (dec, hex, etc).

Upvotes: 2

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506837

int command = line.at(0) - '0';

The numerical values of digit characters are required to be next to each other. So this works everywhere and always. No matter what character-set your compiler uses.

Upvotes: 4

kennytm
kennytm

Reputation: 523154

To convert a numerical character ('0' – '9') to its corresponding value, just substract the ASCII code of '0' from the result.

int command = line.at(0) - '0';

Upvotes: 3

Related Questions