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"<

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.
  • Share the Post:
    Share on facebook
    Share on twitter
    Share on linkedin


    The Latest

    microsoft careers

    Top Careers at Microsoft

    Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

    your company's audio

    4 Areas of Your Company Where Your Audio Really Matters

    Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

    chrome os developer mode

    How to Turn on Chrome OS Developer Mode

    Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS