It is important to note that the std::string classes were actually a wrapper around C style null terminated character pointer string.
Even the apparently sophisticated(and complicated) BSTR of COM era are just a sequence of characters with some meta data(i.e. length of string).
c++ string to char* code
Since we know every std::string actually contains a char * (read character pointer) buffer in the background, there must be some way to convert C++ string to C style char array. The character arrays are also called zero terminated strings.The good news is that there is a function in std::string class which lets us retrieve the const char * which is in the background of the string instance. The method is called
c_str
An exact example in code about how to use std::string.c_str() function is given below.Code C++ string to char * or char array
using namespace std; #include<string> #include<iostream> int main(int argc, char* argv[]) { std::string strILoveYou = "i<3U";// new object of std::string const char * szMe2 = strILoveYou.c_str();// new object of c style null terminated character pointer cout << strILoveYou << endl; cout << szMe2 << endl; return 0; }// code highligting with http://tohtml.com/cpp/
You must have noticed that the const char * retrieved this way is read only. If you want to extract a changeable string out of std::string we'll need to add a couple of lines to the code. We will use the strcpy C function, some might argue that this is not true C++ but I say everything from C is in the genesis of C++ so there's nothing untrue to spirit of C++ if we use functions from the C programming language which is the mother of all languages. The new code will look like
using namespace std; #include<string> #include<iostream> int main(int argc, char* argv[]) { std::string strILoveYou = "i<3U"; const char * szMe2 = strILoveYou.c_str(); char * notConstantCharPtr = new char[strILoveYou.length()]; strcpy(notConstantCharPtr, strILoveYou.c_str()); cout << strILoveYou << endl; cout << szMe2 << endl; cout << notConstantCharPtr << endl; return 0; }// highlight with tohtml.com/cpp
HAPPY CODING FELLAS!!!
I hope you found this small programming tutorial to be useful. Please do check my online courses which are listed on the top right of this page.
สล็อตเว็บตรง Make a fresh new start towards success.
ReplyDelete