C ++ string class c_str () function

Source: Internet
Author: User

The string class of the Standard Library provides three member functions to get the c-type character arrays from a string: c_str (), data (), copy (p, n ).

1. c_str (): generate a const char * pointer pointing to an array terminated with null characters.

Note:

① The data in this array is temporary. When a member function that changes the data is called, the data in the function becomes invalid. Therefore, you can either convert the data first or copy the data to the memory that you can manage. Note.See the following example:

 
constchar* c;string s="1234";c = s.c_str();  cout<<c<<endl;
// Output: 1234s="abcd";cout<<c<<endl;
// Output: abcd

 

If we continue to use the c pointer above, the errors will be unimaginable. For example, 1234 is changed to abcd.

In fact, the above c = s. c_str (); is not a good habit. Since the content pointed to by the c pointer is easy to expire, we should follow the above method. How can we copy the data? This requires strcpy and other functions (recommended ).


//const char* c; //①//char* c;       //②//char c[20]; char* c=newchar;string s="1234";//c = s.c_str(); strcpy(c,s.c_str());cout<<c<<endl;
// Output: 1234s="abcd";cout<<c<<endl;
// Output: 1234

Note: You can no longer write the const value to the const as shown in ① above; nor can you use the uninitialized local variable "c" as shown in ② ", an error occurs.

② C_str () returns a pointer to the character array that the client program can read and cannot modify. You do not need to manually release or delete this pointer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.