Public Group

string to int

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

Recommended Posts

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.

Share on other sites
That all depends on which language/platform you are using.

Share on other sites
Thank you atoi() worked just fine. =)

Share on other sites
Either that, or this. Or boost::lexical_cast. Both only apply to C++, rather than C.

Share on other sites
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 );

Share on other sites
Quote:
 Original post by DrakilorThank 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 extboost::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.

Share on other sites
int final = int.Parse(str);
Sorry, too much C# lately [smile].

• 10
• 18
• 14
• 19
• 15