Archived

This topic is now archived and is closed to further replies.

Convert std string to integer

This topic is 5149 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello! I''m working with std::string and have the following problem: I want to convert a string with the value e.g. "16" to an integer and an integer to a std::string. How to do that? Thanks for every help! -------------------------------------------------------- "If it looks good, it is good computer graphics" "If it looks like computer graphics, it is bad computer graphics" Corrail corrail@gmx.at ICQ#59184081

Share this post


Link to post
Share on other sites
Hi

atoi() takes a const char* as an argument and returns an integer. So you would need to do:


#include<cstdlib>
int i = atoi(string.c_str()); //string is the std::string



You could also use stringstreams instead of atoi() to convert an std::string into an int, something like this


template<typename RT, typename T, typename Trait, typename Alloc>
RT ss_atoi( const std::basic_string<T, Trait, Alloc>& the_string )
{
std::basic_istringstream< T, Trait, Alloc> temp_ss(the_string);
RT num;
temp_ss >> num;
return num;
}



Which you would call as


int x = ss_atoi<int>(string); //string is the std::string



Or you could use boost::lexical_cast from the boost library, see http://www.boost.org for that


[edited by - Jingo on November 13, 2003 8:38:46 AM]

Share this post


Link to post
Share on other sites
Thanks!! I''ll try that!

--------------------------------------------------------

"If it looks good, it is good computer graphics"
"If it looks like computer graphics, it is bad computer graphics"

Corrail
corrail@gmx.at
ICQ#59184081

Share this post


Link to post
Share on other sites