c ++ dynamically generated string array and cutting

FileOpr fopr;
string _PATH_STR =fopr.get_Path();
char *ch = new char[_PATH_STR.length()]();
cout<<ch<<endl;


cout<<strlen(ch)<<endl;

strcpy(ch,_PATH_STR.c_str());

cout<< ch<<endl;

char *ptr;
ptr = strtok(ch,"\\");
while (ptr != NULL) {
printf("ptr=%s\n", ptr);
ptr = strtok(NULL, "\\");
}

Quote from someone else's interpretation

Syntax:
const char * the c_str (); Searching
the c_str () function returns a pointer pointing to regular C string, this string with the content of the same string.
This is for compatibility with c language, no language in the c-string type, it must member function of the c_str string class object () to convert the string to a target string patterns in c.
NOTE: Be sure to use strcpy () function, etc. The method of operation of the c_str () returns a pointer
such as: best not:
char * C;
String S = "1234";
C = s.c_str (); // to point C and finally the trash content, because the object is destructed s, contents of which are processed

This should be used:
char C [20 is];
String S = "1234";
strcpy (C, s.c_str ());
so as not to mistake, the c_str () returns a pointer to temporary, can not be manipulated

As another example of
the c_str () returns in the form of char * string string contains
a function that expects char * parameter, use the c_str () method:
string S = "! The Hello World";
the printf ( "% S", S .c_str ()); // outputs "Hello World!"

Guess you like

Origin www.cnblogs.com/kekezhu0000/p/10949873.html