1

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.

5 Answers 5

4
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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

The C/C++ standard do not guarantee ASCII. They do guarantee that all numerical character codes are adjacent and in asending order so that '5' - '0' will result in 5 though.
Nor is it really C++. See my answer.
2

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).

3 Comments

Yeah, except thats C, not C++.
@mathepic #include <cstdlib> and then use std::strtol().
Yeah, but you have to convert the string to a char *
1

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

Boost has a library for this:

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.