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
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 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
string to a char *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.