string to int
How do i convert a string eg "45" into an int so that the int=45, int(string) is not it since i just get the ASCII value.
boost::lexical_cast is a very powerful type converter, often you're fine with an easier version like this:
#include <sstream>template< typename T, typename S >T lexical_cast( const S& src ){ std::stringstream converter; converter << src; T target; converter >> target; return target;}//usage:int i = 12;std::string str = lexical_cast< std::string >( i );double j = lexical_cast< double >( str );
Quote:Original post by Drakilor
Thank you atoi() worked just fine. =)
atoi actually does not work just fine, it has its odd limitations being rooted in C. The primary concern with it being that on failure this thing returns 0, so you can never really know whether you have actually read a 0 or you have read some nonesense and it decided to say that it was a 0. This is why you need a more versatile approach with better error checking, such as boost's lexical_cast. Get boost here.
Quote:Original post by ext
boost::lexical_cast is a very powerful type converter, often you're fine with an easier version like this:template< typename T, typename S >T lexical_cast( const S& src ){ std::stringstream converter; converter << src; T target; converter >> target; return target;}
You may be fine with this, but this, like atoi, ignores error states (and this is why it is easier to just use boost's lexical_cast), but for completeness sake, modify your code to the following to ensure that errors are dealt with properly:
template<typename T, typename S>T lexical_cast(const S& src) { std::stringstream ss; T target; if (!(ss << src && ss >> target)) throw std::runtime_error("Avast!"); return target;}
You should, of course, replace the exception with a custom exception or change the error message to something slightly more useful than Avast.
Incidentally, the above code is a slight modification to an older version of boost's lexical_cast - the current lexical_cast takes care of a range of the more tricky types to convert as well, and I would suggest always using the boost version, if for no other reason than it is up to date and scrutinised by a lot more people for correctness.
Hope this helps.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement