Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Wednesday, March 2, 2011

String to Char in C++

Checked some posts on the internet, found it very fun, taking notes as below, especially like the 4th one:

string to char*
assuming you allocated the proper space to buf, that should work, but also note, this would work just as well
char *buf = new char[strlen(str)];
strcpy(buf,str);
//...When you are done with buf...
delete []buf;
//the strlen(...) and strcpy(...) functions can be found in string.h 

//std::string s
char *a=new char[s.size()+1]
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());

Method 3:http://www.cplusplus.com/reference/string/string/c_str/     (This is a standard one)
cstr = new char [str.size()+1];
strcpy (cstr, str.c_str());

{notes: } besides, this is a very good example for passing the string into functions, but to first transfer it into some predefinded structure/class, here it use the "vector"

In your sample let 'p' point to the address of the first char of string 'l':
Code:
string l="Pranav";
char *p;
p=&l[0];
As you can see it is possible, however, you have to be carful with this and in most cases you want to let 'p' be const, so you cannot break the inner string structure:
Code:
string l="Pranav";
const char *p;
p=l.c_str();       //c_str returns a pointer to constant char, not a constant pointer to char.

Appendix: Additional question followed from the above, but the explanation is good:
i have another problem though...  
i have a program that accepts an array of string
int func(string pieces[ ])
how do i know how many elements in the array have been passed??
As far as i know "pieces[0].length()" gives the number of characters in a string. however "pieces.length()" doesn't work. plz help...
PS: I am not supposed to use an explicit argument for the number of values passed.

Quote:
int func(string pieces[ ])
In C/C++ you cannot pass an array to a function. Actually this is the same like just using a pointer:
Code:
int func(string *pieces)
Also "pieces.length()" won't work, of course! In C++ (unlike Java) an array is no Object or Data Structure so it does not have any elements you may access with '.' The proper workaound of this is to use a second parameter that holds the length of the array:
Code:
int func(string *pieces, unsinged int length)
But this way you have to "trust" the user that he will call the function correctly..., and in most cases he won't. The best solution is to wrap the array into an object, encapsulate the data and use members to access them. But you aren't the first one who came across this problem, so you needn't to write this class by yourself, instead use "vector": This is part of the STL an will do what you want:

--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

No comments:

Post a Comment