Crayon Shin Chan wrote:Question: c_str() converts from a C++ string object to a C string (an array of chars, I heard)? Why is that needed?
As I said, char* or char in C is just a pointer to a contiguous block of memory, not a real C++ object. std::string is
an object. A lot of people who grew up on Java/C#/etc often miss this. Grab a good C book and really understand pointers please (definitely not going to recommend K&R, but "C Primer Plus" is good). So using .c_str() returns a const pointer (don't mess with it!) where you can pass in to functions that take const char*.
Crayon Shin Chan wrote:Why should I even take the time to convert it to back to a character array (const char *aaa as Madman said)?
I think he was just illustrating. When doing mixed C/C++, try to stay with C++ strings/stringstream until the last possible moment to do c_str(). If you don't need to pass into some C function then no need.
Crayon Shin Chan wrote:It seems the arguments are provided as arrays of strings. Why do you call them arrays of chars, because if they are arrays of chars (which are C strings right) then each increment of the index should point to a different letter of the arguments?
Again, char*/char != string objects. argv is actually an array of char pointers, which in theory each member can be pointing to different blocks of memory containing the arrays of characters all over your process space.
Crayon Shin Chan wrote:How do I convert from argv to a string?
Either you use good old fashion s[n]printf (or s[n]printf_s on Windows with VC++) then you can stay with char*, or if you are going to use C++/Boost's real string functions, that is easy to do:
- Code: Select all
This constructs a new string object (separate storage in memory). In the general case of course you have to be careful of the implications of that memory allocation.
Re: printf vs iostream - These days I don't do much of that because of localization. It is almost either FormatMessage or boost::format. Of course for some quick internal concat and stuff I'm actually all for stringstream (strcat/strncat is now falling out of favour due to those now infamous overflows).