C++ examples for STL:string
Convert a string object into a null-terminated string.
#include <iostream> #include <string> #include <cstring> using namespace std; int main()//from ww w. ja va 2 s . c o m { string str("This is a test."); char cstr[80]; cout << "Here is the original string:\n"; cout << str << "\n\n"; // Obtain a pointer to the string. const char *p = str.c_str(); cout << "Here is the null-terminated version of the string:\n"; cout << p << "\n\n"; // Copy the string into a statically allocated array. if(sizeof(cstr) < str.size() + 1) { cout << "Array is too small to hold the string.\n"; return 0; } strcpy(cstr, p); cout << "Here is the string copied into cstr:\n" << cstr << "\n\n"; // copy the string into a dynamically allocated array. try { char *p2 = new char[str.size()+1]; strcpy(p2, str.c_str()); cout << "String after being copied into dynamically-allocated array:\n"; cout << p2 << endl; delete [] p2; } catch(bad_alloc ba) { cout << "Allocation Failure\n"; return 1; } return 0; }