Reputation: 888
char* a = new char[50];
This is for a school assignment. I am not allowed to use strings or vectors or anything else. Just char array.
Lets say I want to do cin >> a;
and I don't know the size of the input. How should I put it in char array? The above only works for a small size of input.
Should I do this? char* a = new char[some_large_number];
or is there a better way?
I can only use (dynamic) char arrays.
EDIT: The input can be any string like
abcd
or even somelongrandomsentecewithoutspsomelongrandomsentecewithoutspacessomelongrandomsentecewithoutspaces
Upvotes: 2
Views: 4414
Reputation: 726599
This is a little tricky with character arrays: what you need to do is tell cin
that you do not want to receive more than a certain number of characters (49 for a 50-character buffer, because you need space for null terminator). When the read is finished, check the length of the string. If it is 49, allocate a new, larger, string, copy the old string into it, and continue reading. If it is less than 49, the end of string has been reached.
You can use istream::get
to read the data into your buffer:
cin.get(a, 50); // You can specify an optional delimiter as a third parameter
Note that you pass 50 for the length, and get
will subtract 1 automatically, because it knows about the space needed for null terminator.
Upvotes: 9