c_str()

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.
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
L B wrote:
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.

http://c-faq.com/
http://en.cppreference.com/w/c

And for fun mostly:
http://crypto.stanford.edu/~blynn/c/index.html
Last edited on
Most functions and libraries take char pointers as arguments, not std::string. That is why this code gives an error.
1
2
std::string fileName( "myData.dat" );
std::ifstream( fileName );

But this code works.
1
2
std::string fileName( "myData.dat" );
std::ifstream( fileName.c_str() );

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. 
vasilenko93 wrote:
the reason it points to a null-terminated string because it was not yet initialized.

It's always null-terminated. The null character '\0' (byte value zero) marks the end of the string.
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 ;)
L B wrote:
@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.
@Catfish: OK, you win this time, but as soon as C++1y/14 comes out I will stop "supporting" C++03.
Last edited on
@Catfish it's visual studio express 2010
Topic archived. No new replies allowed.