c_str returns a const char* that points to a null-terminated string i still don't get it can someone please explain to me giving simple example what is c_str() and when it's used
In C, there is no std::string class, so all strings in C are represented as arrays of characters. The only reason to use c_str() in C++ is if you need to interact with C code.
The only reason to use c_str() in C++ is if you need to interact with C code.
Or you need to open a file stream in good old C++98 but you used an std::string to store the filename. Something they could have easily fixed in C++03 (five years later) but didn't.
Sharan123 wrote:
Do i need to understand C first to understand SDL i know all the basics of c++ but there are some function which are completely new to me
All you need to do is expand your knowledge. In fact I'm not even sure if I'm answering a question.
The std::string class contains a private char* member. When you use string functions like = and + the class does all the hard work for you, and when you need direct access to the char pointer you simply calls c_str(); Also the reason it points to a null-terminated string because it was not yet initialized.
1 2 3 4
//The following code is useless for you
std::string name;
std::cout << name.c_str();
//Because name was not initialized with anything.
It should be noted that std::string is length-terminated and not null-terminated, and as such it is capable of containing the null character in the muddle of it with no issue.
@Catfish: It's 2014, I will not pretend C++11 is new anymore ;)
@Catfish: It's 2014, I will not pretend C++11 is new anymore ;)
This is about recognizing that a lot of people still don't use C++11 compliant tools.
I said this same thing to vlad back in the day: I think C++98 should still be treated as the default standard, and we should make it clear when we give C++11 code or talk about C++11 features.
@ Sharan123: please say what compiler/IDE you are using.