Archived

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

ironfroggy

std::string compares

Recommended Posts

Guest Anonymous Poster
>what is the str::string equiv to strcmp()? also, how can i get a pointer to the actual char array in the string object?

I''m not entirely sure on the first question (assuming you want a numerical answer) but you can do the following, which answers the second question:

string bob("bob"), alice("alice");

if (strcmp(bob.c_str(), alice.c_str()) {/* blah blah blah */}

Note the return type of c_str() is const char*.

Share this post


Link to post
Share on other sites
Well, there's the compare function that returns an int just like strcmp :

    
string str1("hello");
string str2("world!");

if(str1.compare(str2) == 0) blah;


But you can also use all of the comparison operators: < <= == != >= >.

Keep in mind that std::string doesn't use a terminator. If you want a pointer to the array, both c_str and data do this—both return const char* . c_str adds a terminator to the array so you can use it anywhere where a terminator is necessary, such as printf . If you want just the characters in the array that make up the string, use the data function.


Edited by - merlin9x9 on August 2, 2001 2:28:51 PM

Edited by - merlin9x9 on August 2, 2001 2:29:24 PM

Share this post


Link to post
Share on other sites
Small question......

I''m using the SGI stl with vc6.0

and i get one memory leak each time of a string
the last string that i accessed through c_str()

its rather strange but i think it might just be VC''s memory leak detection

Share this post


Link to post
Share on other sites
Most leak-detection programs (MSVC, BoundsChecker in my experience) have difficulty detecting the freeing of static data; e.g. things that are freed by atexit handlers from libraries. The reason is that the leak detection is usually loaded as a DLL, and has no control over when it''s unloaded. We had a "leak" reported that we knew we were freeing in MSVC, so we put a breakpoint in the destructor of the static object (singleton), and it did hit the breakpoint--after the the memory leak list had been printed in the window.

So, in summary, not all leaks are leaks.

BUT, in your case, I don''t think c_str () should be leaking at all. I have never seen anything like that. I would be concerned if I were you, though I haven''t used your STL implementation.

Share this post


Link to post
Share on other sites
I think it was at the official SGI STL download site where I saw a note saying their STL implementation made some leak-detectors unhappy, so Stoffel is exactly right—your STL is fine. As a matter of fact, it''s the one I use.

Share this post


Link to post
Share on other sites