Click here to Skip to main content
14,825,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am taking in as a string "str" from the user.
Let suppose user entered str=123456789

I want put that numbers in character array "ch1" without predefining the char array.
so that "ch1" character should have the size 9 automatically and ch1[0]=1 and ch1[1]=2 and so on....
Sergey Alexandrovich Kryukov 26-Aug-11 15:47pm
What do you mean by "string"? std:string, char*, LPWSTR, what? In all cases the problem looks trivial. What seems to be difficult to achieve?

You can use c_str[^] for your purpose.
Philippe Mori 26-Aug-11 18:37pm
This is effectively a good solution except if he want to modify the data in the array...
If you don't want an array with predefined size then you should allocate it dynamically (and remember to delete it when is no longer needed), for instance, assuming str is an instance of std::string, we have:
char * ch1;
ch1 = new char[str.size()+1]; // +1 makes room for string terminator 
strcpy(ch1, str.c_str());
delete [] ch1;
Philippe Mori 26-Aug-11 18:38pm
It would be preferable to use a std::vector<char> for that purpose...
Anthony Mushrow 26-Aug-11 19:59pm
Why would std::vector be better? The only thing you'd really get our of it is not having to remember the delete, plus some overhead for going through the container. If the size of the array isn't going to change after it was created I don't really see any advantage.
Philippe Mori 26-Aug-11 20:08pm
Not having to worry about delete[] is the main advantage. And you can even get a pointer to the first element if you really need C-style access to the data (maybe to pass it to a C DLL).

It does help ensure correct code even if an exception occurs and if the code contains multiple returns or if the code is modified 6 months later... Thus in the end, it does help.
CPallini 5-Sep-11 9:32am
Oh yes, if you gloss over the OP's specific requirement.
If you would like to do something like

std::string str = !23456789";

// This is invalid...
char ch1[] = str;  

// None of the alternative below are valid.
//char ch1[str.size()] = str;  
//char ch1[] = str.c_str();    
//char ch1[str.size()] = str.c_str();  

In C++, you cannot do something like that. C style array must have a size determined at compile time and there is no way to initialise such an array from a string other than a C-style string defined in code.

Here is a much better alternative if you need to modify the content. If not, then simply use string operator [] or the result of c_str().

std::string str = "123456789";
std::vector<char> ch1(str.begin(), str.end());

// You can know use ch1 almost like an array...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900