tags:

views:

131

answers:

5

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.

+2  A: 
KennyTM
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.
Martin York
Nor is it really C++. See my answer.
graham.reeds
+3  A: 
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.

Johannes Schaub - litb
+2  A: 

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

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

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

Boost has a library for this:

int i = boost::lexical_cast<int>(str);
FredOverflow
+1  A: 

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.

graham.reeds