Possible Duplicate:
How to parse a string to an int in C++?
I have done some research and some people say to use atio and others say it's bad, and I can't get it to work anyways.
So I just want to ask flat out, whats the right way to convert a string to a int.
string s = "10"; int i = s....?
Thanks!
In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
ToInt32(String) method to convert an input string to an int.
In C++11, use std::stoi
as:
std::string s = "10"; int i = std::stoi(s);
Note that std::stoi
will throw exception of type std::invalid_argument
if the conversion cannot be performed, or std::out_of_range
if the conversion results in overflow(i.e when the string value is too big for int
type). You can use std::stol
or std:stoll
though in case int
seems too small for the input string.
In C++03/98, any of the following can be used:
std::string s = "10"; int i; //approach one std::istringstream(s) >> i; //i is 10 after this //approach two sscanf(s.c_str(), "%d", &i); //i is 10 after this
Note that the above two approaches would fail for input s = "10jh"
. They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):
int to_int(char const *s) { if ( s == NULL || *s == '\0' ) throw std::invalid_argument("null or empty string argument"); bool negate = (s[0] == '-'); if ( *s == '+' || *s == '-' ) ++s; if ( *s == '\0') throw std::invalid_argument("sign character only."); int result = 0; while(*s) { if ( *s < '0' || *s > '9' ) throw std::invalid_argument("invalid input string"); result = result * 10 - (*s - '0'); //assume negative number ++s; } return negate ? result : -result; //-result is positive! }
This solution is slightly modified version of my another solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With