Inputting strings into char arrays without knowing array size

I really have two questions. The first one I think I already know the answer to, but confirmation would be nice: Is it a bad idea to read data into an array if you do not know the size of the array?

Secondly, is there a way to input a string and store it in a char array without knowing the size of the array? All of the functions I have seen require the size of the array to be passed in. However, the lab question I am working on simply states: "Read a string into character array variable state." I need to write the code to accomplish that. There is no definition of the "state" array, nor of its size. I wrote a line where I assumed the size of the array, but I am curious to know if there is a way to accomplish the same thing without specifying the size of the array.
Is it a bad idea to read data into an array if you do not know the size of the array?


It depends on the situation. Sometimes you can assume the array will be large enough to hold the string.

But usually -- yes -- it's a very bad idea.

Secondly, is there a way to input a string and store it in a char array without knowing the size of the array?


Why can't you know the size of the array?

It almost sounds to me like you need to just pick a size for this array and use that. Try to pick one that will be large enough to hold any (reasonable) input.
@Disch: Thanks for the response. That is essentially what I did in my answer to that particular question. I assumed a maximum of 100 characters in the array and wrote the code for that input. I just wanted to make sure I wasn't missing another way to do it.
another way to go about this problem is vectors!
look up the push_back method for the vector class, something along the lines of,
vector_name.push_back (item_to_put_in_vector);
hope this helps!
Well since he's working with string data the logical choice would have been a std::string. But I assume this was an assignment that specifically required char arrays.
Topic archived. No new replies allowed.