Good news: std::string has a wonderful member function c_str(). It returns a const pointer to the C-style version of the invoking string.
Now you may use all power of old good str family. Don't modify the string contents via forcibly casted as non-const pointer obtained from c_str()!
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
Rush after prev post (an example and the answer to the question):
std::string stlString("Don\t tread on me!");
char IloveC[2008];
strcpy(IloveC,stlString.c_str());
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
If you really want to know how to convert a string to an array:
char strarray[100];
string str = "Hello";
for(int i = 0;i < str.length();i++)
strarray[i] = str[i];
This will work, but in future when copying variables like this from a vector, try to do it like this:
char strarray[100];
string str = "Hello";
int arrayLength = str.length();
for (int i = 0; i < arrayLength; i++)
strarray[i] = str[i];
By using a variable to store the array length you do not need to call the.length() function for every cycle of the loop and will speed things up in more extreme cases.
Another way to access the char array is to simply get the pointer at the start of the string like this.
string str = "Hello";
char *cstr = &str[0];
Also this way the pointer isn´tconst unlike the return value from the string::c_str() function.
(The only problem with this is that it is not a seperate char array, anything you change in cstr will also change in str).
Hope this helps.
William Hemsworth
Posting Virtuoso
1,591 posts since Mar 2008
Reputation Points: 1,429
Solved Threads: 129
char strarray[100];
string str = "Hello";
int arrayLength = str.length();
for (int i = 0; i < arrayLength; i++)
strarray[i] = str[i];
1) Don't use[CODE=CPP] use instead [CODE=CPLUSPLUS]
2) The code above contains the same bug as the version previously posted. Q: What is the bug? A: The resulting string is not null terminated.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Well it's an easy fix isn't it? >_>
char strarray[100] = {0};
string str = "Hello";
int arrayLength = str.length();
for (int i = 0; i < arrayLength; i++)
strarray[i] = str[i];
Yes, it is an easy fix. What you did is one way to do it. The other way is to simply add another line starray[i] = 0; after the end of the code snippet (line 7). This is probably preferred because it insures the string is correctly null-terminated no matter how many different strings that are copied into the character array.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343