William M. answered 12/15/19
College Professor of C++ with 7+ years of teaching experience
We can get access to the underlying C string
using std::string's c_str() method, but we cannot change the string.
Like so:
#include <iostream>
int main(int argc, const char* argv[]) {
std::string s = "Standard string";
const char* p = s.c_str(); // this gives access to the C string
while (*p != '\0') {
std::cout << (char)toupper(*p++) << " "; // string not changed
}
std::cout << "\nThat's all\n";
return 0;
}
//----------- OUTPUT ------------------------------
S T A N D A R D S T R I N G
That's all
Program ended with exit code: 0
If we wanted to manipulate the underlying C string, and then create a new std::string, we would have to duplicate or copy the underlying C string to a new buffer, then construct a new std::string from the modified C string.
Hope that helps.