I want to write a pair of functions, one that converts a character array into a string and one that converts a string into a char array. I have tried and failed miserably. Here's one attempt at converting a string to a char array:
#include <iostream>
#include <string>
using namespace std;
char * String ToChar(string String);
int main()
{
string test = "hello world";
char array[] = StringToChar(test);
cout<<"test = "<<test<<" array = "<<array<<endl; // hopefully, test and array will match
return 0;
}
char * StringToChar(string String)
{
// pre: String is a nonempty, initialized string
// post: foo is a character array identical to String in content and length
const int size = String.size();
char foo[size];
for (int i = 0; i < size; i++)
foo{i}<I> = String{i} <I>;
char* fooPtr = foo;
return fooPtr;
}
Needless to say, this above code won't even compile. There are several issues that I see:
1) how to dynamically size the array foo (impossible?)
2) how to actually return the array to main (use pointers as shown?)
3) how to assign the returned value to array in main
Could someone please advise / write me something that works?
~Rapier21
</I></I>
#include <iostream>
#include <string>
using namespace std;
char * String ToChar(string String);
int main()
{
string test = "hello world";
char array[] = StringToChar(test);
cout<<"test = "<<test<<" array = "<<array<<endl; // hopefully, test and array will match
return 0;
}
char * StringToChar(string String)
{
// pre: String is a nonempty, initialized string
// post: foo is a character array identical to String in content and length
const int size = String.size();
char foo[size];
for (int i = 0; i < size; i++)
foo{i}<I> = String{i} <I>;
char* fooPtr = foo;
return fooPtr;
}
Needless to say, this above code won't even compile. There are several issues that I see:
1) how to dynamically size the array foo (impossible?)
2) how to actually return the array to main (use pointers as shown?)
3) how to assign the returned value to array in main
Could someone please advise / write me something that works?
~Rapier21
</I></I>