+ 1
Can I convert a string to an array of chars in c++?
I want to do things like checking for spaces or reversing a string, which I can do if a string can be made into an array. Can someone help me out? I know char foo[]="Hello"; will make an array. But is it possible to do something like this? cin>>my_string; char foo[]=my_string.tochar();
4 Respuestas
+ 4
Simplest way I can think of doing it is:
string temp = "cat"; char tab2[1024]; strcpy(tab2, temp.c_str());
For safety, you might prefer:
string temp = "cat"; char tab2[1024]; strncpy(tab2, temp.c_str(), sizeof(tab2)); tab2[sizeof(tab2) - 1] = 0;
or could be in this fashion:
string temp = "cat"; char * tab2 = new char [temp.length()+1]; strcpy (tab2, temp.c_str());
https://stackoverflow.com/questions/13294067/how-to-convert-string-to-char-array-in-c
and
https://www.sololearn.com/learn/CPlusPlus/1623/?ref=app
0
Thank you. I think I'll use the third one.
Or if I make sure that temp is the expected size, I can use the first one.
0
Thank you very much. I understood now.
0
سلام