casting std::string

Started by
5 comments, last by Will F 17 years, 5 months ago
I'm using the this following piece of code: int num =0; std::string myString; num = (int)myString.c_str(); to turn an std::string into an int value to be stored elsewhere. It doesn't work the same everytime though. num is given a different value for the same string. Why is that? Would I better off to write my own string to int function?
Advertisement
If you have the boost library, you can use boost::lexical_cast<int>(myString);

If you dont have boost, consider getting it, its great.

Otherwise you can write something like:

#include <sstream>template< class Output, class Input >Ouput cast( const Input &in ){   Output out;   std::stringstream stream;   stream << in;   stream >> out;   return out;}


And then use:

num = cast<int>(myString);
You can't just cast like that. First why do you try to convert it to a c-string? It might get rid of any compile-time errors, but that just means you have moved them to runtime which is much harder.

What happens in your case is that c_str returns a const char*, which points to the start of the string. When you cast to int this address is converted, so you basically get the address of the string in memory (that's not exactly how it works, but close).

What you need is some function for converting the string, the best idea would be to use Boost.lexical_cast (a part of Boost). If you for some reason (you better have a good one) refuses to use Boost you can use string streams to do the conversion:
int num = 0;std::string myString;std::stringstream ss;ss << num; // Read the numberss >> myString; // Write to string

However using lexical_cast is superior.
What you're doing there is converting a pointer (a char*) to an integer, this just gives you an (essentially random) location in memory as a number. To do what you want there's a couple of different ways.

A) If you use the boost library (which IMHO most people should) you can use boost::lexical_cast<int>(myString)

B) Use std::stringstream (this is what boost::lexical_cast does internally)
int value;std::stringstream strm(myString);myString >> value;

C) Use the old C functions to convert the character array returned by myString.c_str() (not recommended, but is still an option)

EDIT: Way too slow.....
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V
The code you've posted isn't converting the string to an integer it's converting the address of the first character of the internal character array, to an integer.

Firstly, boost::lexical_cast or std::stringstream is what you need for what you're trying to do.

Secondly, you should look into learning the C++-style casts, (google for static_cast, reinterpret_cast, const_cast), and use them instead of C style casts. Using C++ style casts will force you to think about why you are trying to cast one type to another, and will also help to catch logical errors like this at compile time.
Thank you for the quick responses. It makes sense now why it wasn't working. I currently haven't used the boost library before, but it is something i'll look into. I'll use the stringstream method for now. Thanks again for all the help.
Quote:Original post by klayAlloy
I currently haven't used the boost library before, but it is something i'll look into. I'll use the stringstream method for now.


I highly recommend looking into boost when you have the time, there's a lot of useful code in it. Plus it'll give you a head start on some of the features that will be in the next C++ standard (and are currently in Technical Report 1).

This topic is closed to new replies.

Advertisement