Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: All
May 12, 1998

Using a string object in a context requiring a "read-only" char*

The advantages of a string object over a C-style char* are obvious. Yet there are times you may still need a null-terminated char*, for example, when legacy C code is still being used in your programs. The standard string class has the c_str() member function which returns the const char* representation of its object:
 
void f() 
{
string  s;
s = "Hello";

if( strcmp( s.c_str(), "Hello")== 0) //are they identical?
cout <<"identical"<<endl;
		else 
cout<<"different"<<endl;
	}
Please note:
  • The const char* returned from the c_str() member function is owned by the string object, therefore, you should not attempt to delete it.
  • It points to a valid char* as long as you do not call any non-const member function of the string object.
  • Danny Kalev
     
    Comment and Contribute

     

     

     

     

     


    (Maximum characters: 1200). You have 1200 characters left.

     

     

    Sitemap
    Thanks for your registration, follow us on our social networks to keep up-to-date