assigning user input string to a char array

Oct 6, 2015 at 8:04pm
I had a problem with the line below, it says it can't convert string to char. I've tried using string.c_str()but ended up getting a mess of errors - I could be using it wrong though.
1
2
string y;  
char x[y.length()] = {y}; //where y is a user input via getline 


Why is it that you can initialize an array of chars like:
 
char x[] = "blah blah";


But if you set that string equal to some string variable it doesn't work?

For context, I'm trying to read in a string from the user via terminal and store it into an array of chars NOT preset to any constant value like 999. It's supposed to read the input, say 4 letters, and output an array of chars of size 4 - which I have managed to do. It's just, actually getting the user inputted string to go into the array is the problem.

Oct 6, 2015 at 8:42pm
1) Array size should me know at compile time
2) Assigment or copy initialization does not work properly with arrays.

you will need:
a) allocate memory for your array (you will need y.size() + 1 elements: do not forget terminating 0)
b) Copy characters from string to array.
c) deallocate memory when you are done with array.
Oct 6, 2015 at 11:14pm
so what I'm trying to do is impossible? unless I set my char array to a constant size?
Last edited on Oct 6, 2015 at 11:39pm
Oct 6, 2015 at 11:55pm
unless I set my char array to a constant size?
Or dynamically allocate one (with all implicatons of this)
Oct 7, 2015 at 11:44pm
figured out how to do what I wanted to do via
http://www.cplusplus.com/doc/tutorial/dynamic/
Topic archived. No new replies allowed.