Conversion Between char* and string

◀ Parsing a string▶ Show How Much Time Has Passed
Amazon Here the term “string” refers to C++ string class. In general, even though char array is string’s underlying implementation, string is a better choice than char* because of easy manipulations such as appending a string to another string, extracting a string from a long string, and inserting a string into another string.

However, some functions provided by C++ libraries can be called only with arguments of certain types. In this case, conversion char* to string and vice versa will come in handy.
To convert char* to string, simply use the assignment operator. To convert string to const char*, simply use c_str() function provided by <string> or <string.h>. Here is a sample program to demonstrate both conversions:
#include<string>  /* or <string.h> */
int main() { char* c="firstString"; string s; const char* c2; string s2="secondString"; s=c; c2=s2.c_str(); cout<<"c is "<<c<<endl; cout<<"s is "<<s<<endl; cout<<"c2 is "<<c2<<endl; cout<<"s2 is "<<s2<<endl; return 0; }
Note that c2 is of type const char*, not char*. Conversion between string and const char* comes in handy when, for example, the program expects a string entered by user, then the program converts the string to const char* by using c_str() so that open() that <fstream> provides can take that argument.


If you really need to convert string to char*, not const char*, you can use the following function:
#include<iostream>
#include<string.h> 	// or <string>
char* convertStringToCharStar(string s){
	int i;
	char* tempc=new char[s.length()];

	for(i=0; i<s.length(); i++)
		tempc[i]=s[i];
	return tempc;
}
◀ Parsing a string▶ Show How Much Time Has Passed

fShare
Questions? Let me know!