need to convert a c++ string into c string

I can't seem to find a good example on the internet on how to convert a c++ string into a c string. I'm using a function to transfer a c++ string so then i can convert into a c string and then return a pointer. Here is what i have so far for the function. really lost.

1
2
3
4
5
6
  int* getString(const string line)
{
	const int length = line.length();
	char line2 = [length];

}
since you declared line as a string, then, line.c_str() is the character(const) pointer to its c string equivalent. See the reference(given) above for more info though.
btw, wouldnt it be better to have char* as the type of that function? :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

char* func(string s)
{	
	int  size = s.length();
	char *ch = new char [size+1];
	
	for(int i=0; i<size; i++)
	{
		ch[i] = s[i];
	}
	ch[size] = '\0'; //required
	
	return ch;
}

int main ()
{
	string s = "hello world";
	
	char *c;
	
	c = func(s);
	
	cout << c;	
	
	delete[] c;

return 0;
}
C++11 has this built in so you can just pass in the string.
Topic archived. No new replies allowed.