What is the purpose of C_str() in C++?

✅ Answers

🥇 Favorite Answer

  • In C++, the internal representation of a string is hidden. As a user you don’t know and shouldn’t care what a string variable actually looks like on the inside. You access it and operate on it all using the standardised member functions such as at(), size(), length(), replace(), and so on.

    But sometimes you will need an old C style string representation of the C++ string object. Namely a sequence of characters terminated with a NULL byte. Often older APIs or external libraries will need a C style string. In this case you use C_str() to get a pointer to a const representation of the C++ string object. Note that because it is a const pointer, you can’t modify the underlying string through this pointer.

  • To produce a C compatible string for C libraries and functions.

  • C_str In C

    Source(s): https://shrinkurl.im/baxqe

  • you can use c_str() like this…

    ifstream myfile;

    string filename;

    myfile.open(filename.c_str()); // when normally you would just do myfile.open(“file.txt”);

    Source(s): Just used it in c project

  • See also  My TI keeps rounding to the wholest number only?

    Leave a Comment