std::string compares

Started by
6 comments, last by ironfroggy 22 years, 8 months ago
what is the str::string equiv to strcmp()? also, how can i get a pointer to the actual char array in the string object?
(http://www.ironfroggy.com/)(http://www.ironfroggy.com/pinch)
Advertisement
>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*.
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
Thanks alot that helped me very much!
(http://www.ironfroggy.com/)(http://www.ironfroggy.com/pinch)
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
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.
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.
thank you.

This topic is closed to new replies.

Advertisement