String to char array

Hello, I'm attempting to write a function that converts a string into an array of characters. This is for an encoding project I have to work on. However, my code doesn't seem to work. Any help would be appreciated.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

 char _stringtochar_(string y,char x[501])
{

for(int i = 0;i < y.length();i++)
 { x[i] = y[i];
	return x[i];
 }
}

int main()

{
	string trial = "Hello";
	char messagearray[501] ;
	for (int j = 0; j < 502; j++)
	_stringtochar_(trial,messagearray);
	cout << messagearray[1] << endl;
	
}
for (int j = 0; j < 502; j++) I don't see why you have this loop. It looks like you are just doing the same thing 502 times.

The return statement in _stringtochar_ will end the function so the loop in that function doesn't have any effect. My guess is that you don't want the return inside the loop. The return value is never used, so what exactly is it you want the function to return?

Why do you want to convert the string to a char array anyway? Can't you just change the chars in the string through operator[]?
c_str will return the char array of the string.
1
2
3
std::string S = "String";
char* C = new char[S.size()+1];
strcpy (C, S.c_str());
Last edited on
Topic archived. No new replies allowed.