Hi.
I want to convert a string into an array of chars but I have no idea how to do it. Someone please help.
Printable View
Hi.
I want to convert a string into an array of chars but I have no idea how to do it. Someone please help.
The function is 'std::string::c_str()':
ViggyCode:std::string myString = "This is my string!";
const char *pArrayOfChars = myString.c_str();
assert(pArrayOfChars[2] == 'i');
It could be something like:
Albert.Code:#include <string>
#include <iostream>
using namespace std;
#define SIZE 30
int main(void)
{
string sStr="Hi, World";
char sArr[SIZE];
memset(sArr, 0, SIZE); //Inicialize array
memcpy(sArr, sStr.c_str(), strlen(sStr.c_str())); //copy Array
cout << sArr << endl;
}
Thanks viggy, but i do not fully understand it. Could you add comments on each line please?
No, there is no need for that. I solved it thanks to albert's advice ^^ thanks albert!
Or, if you don't need your own copy, I'd stick with Viggy's advice:
JeffCode:#include <string>
#include <iostream>
using namespace std;
int main()
{
string sStr ="Hi, World";
const char* sArr = sStr.c_str();
cout << sArr << endl;
}
Writing void like that is redundant in C++ and doesn't make it look good.Quote:
Originally Posted by AlbertGM
No need to initialize this way - setting the first character to '\0' is enough for C-style strings.Quote:
Originally Posted by AlbertGM
Prone to going beyond sArr buffer size. Either provide a check for sStr length and SIZE or use dynamic allocs.Quote:
Originally Posted by AlbertGM
//Are you fat Albert from Hitch? :) kiddin'.. ;)
I tried using memcpy and by using viggy's method but each time i get an error saying that c_str() is not declared
Post your code, please.Quote:
Originally Posted by Tsubasa
Jeff
convert a string to char array???
a std::string IS a char array!
well not explicitly by stl....
and what is a "string"? is it char x[] = "ASDF" or char* x = "ASDF"; or std::string x = "SDFG" or CString x = "ASDF"; or wchar_t or TCHAR isntead of char.. or something else??