开发者

converting string to int

hello i have a problem i am trying to convert a string like "12314234" to int so i will get t开发者_如何转开发he 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.


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.


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


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


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

Boost has a library for this:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜