String: c_str (), string: c_data (), and correct conversion between string and char *

Source: Internet
Author: User

String: c_str:

The Return Value of the c_str function is const char * and cannot be directly assigned to char *. Therefore, we need to perform corresponding operation conversion. below is the conversion process.
The C ++ language provides two string implementations. The original one is the C language implementation of the string. Like other parts of the C language, it is available in all implementations of C ++. we classify the string objects provided by this implementation as C-strings, each C-string is of the char * type.
The standard header file <cstring> contains a function library that operates C-strings. These library functions express almost every string operation we want to use. When you call a library functionProgramThe string type parameter is provided, while the library function uses a C-string internally. Therefore, the string object needs to be converted to a char * object, while c_str () provides a way to return a pointer to a character array that is readable and unchangeable by a client program. Example:

 1   # Include  <  Iostream  >  
2 # Include < String >
3 Using Namespace STD;
4 Void Main ()
5 String Add_to = " Hello! " ;
6 // STD: cout <add_to <Endl;
7 Const String Add_on = " Baby " ;
8 Const Char * Cfirst = Add_to.c_str ();
9 Const Char * Csecond = Add_on.c_str ();
10 Char * Copy = New Char [Strlen (cfirst) + Strlen (csecond) + 1 ];
11 Strcpy (copy, cfirst );
12 STD: cout < Copy < Endl;
13 // Strcat (copy, csecond );
14 Add_to = Copy;
15 Delete [] copy;
16 STD: cout < Add_to < STD: Endl;

Simple Example:
Const char * c_str ();

The c_str () function returns a pointer to a regular C string with the same content as this string.
This isC LanguageCompatible. There is no string type in the C language. Therefore, you must use the member function c_str () of the string class object to convert the string object to the string style in C.
Note: Use the strcpy () function to operate the pointer returned by the c_str () method.
For example, it is best not:

1 Char*C;
2 StringS="1234";
3 C=S. c_str ();
//C finally points to the garbage content, because the S object is destructed and its content is processed (correct: the structure of the S object is carried out after the value assignment operation is completed on the pointer C, so there is no error)

It should be used as follows:

1 CharC [20];
2 StringS="1234";
3 Strcpy (C, S. c_str ());

In this way, no error occurs. c_str () returns a temporary pointer and cannot be operated on.
Another example
C_str () returns the string containing the string in the form of char *
If a function requires the char * parameter, you can use the c_str () method:

1 StringS="Hello world!";
2 Printf ("% S", S. c_str ());//Output "Hello world! "

C_str:
When you need to open a file whose file name is input by the user, you can write ifstream in (St. c_str ());. Where st is of the string type, it stores the file name entered by the user.

 

String: c_str (), string: c_data:

 

Const value_type * c_str () const;

Const value_type * Data () const;

 
Data only returns the original data sequence. it is not guaranteed that traits: EOS (), or '\ 0' will be used to end the string. Of course, most implementations may have done this.

C_str is a standard practice. The returned char * must point to a valid C-compatible string terminated with '\ 0.
Therefore, if C-compatible strings are required, c_str is the standard practice, and data does not guarantee the consistency of all STL implementations.

 

You may ask, if the c_str () function contains data (), what else do you need the data () function? Look at the source code:
Const chart * c_str () const
{

If (length () = 0)

Return "";

Terminate ();

return data ();

}< br> the original c_str () process is: first call terminate (), then return data (). Therefore, if you have high requirements on efficiency and your processing may not end in \ 0 mode, you 'd better choose data (). However, for General C functions, you need to use const char * as the input parameter, and you need to use c_str () function.
for the c_str () data () function, the returned array is owned by the string itself and cannot be modified. The reason is that many strings adopt the reference mechanism during implementation. That is to say, several strings may use the same character storage space. And you cannot use sizeof (string) to view its size. For detailed explanations and implementations, see article 15 of objective STL: be careful about the diversity of string implementations.
In addition, you can use c_str () or data () to obtain the string only when needed. Each call will expire when you use it again, for example:
string strinfo ("this is winter");
...
// The best method is:
Foo (strinfo. c_str ();
// this can also be used:
const char * pstr = strinfo. c_str ();
Foo (pstr);
// do not use pstr any more. The following operations make pstr invalid.
strinfo + = "Hello! ";
Foo (pstr); // error!
what are the errors? When you are lucky, pstr may just point to "this is winter hello! "String, if not lucky, it will lead to other problems in the program, there will always be some unexpected errors. In short, it will not be the expected result.


Supplement: string is a C ++ class, so use the C ++ function to operate the string class as much as possible. It corresponds to Standard C and char *.


[Thank you for your reference]
Http://baike.baidu.com/view/1600698.htm
Http://www.cnblogs.com/lancidie/archive/2011/03/17/1987130.html

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.