Convert std string to integer

Started by
1 comment, last by Corrail 20 years, 5 months ago
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
--------------------------------------------------------There is a theory which states that if ever anybody discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.There is another theory which states that this has already happened...
Advertisement
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]
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
--------------------------------------------------------There is a theory which states that if ever anybody discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable.There is another theory which states that this has already happened...

This topic is closed to new replies.

Advertisement