I am doing an assignment where the first part requires us to prompt the user to enter a string. We need to store this input as a cstring on the heap (not a std::string so we get a better understanding of cstring). I have got something that works fine:
char *input = new char[500];
cout << "enter a string: ";
cin.getline(input, 500);
But I feel like this isn't a very good way to do it in regards to creating an array of 500 and hoping they don't exceed this character limit. Is there a way I can do this without making a ridiculously large array and likely not using anywhere near that much? This seems a very amateurish way of going about it. I think it is possible using std::string but I have to use cstring :(
std::stringprobably does it is by allocating a smallish buffer, then reallocating and copying once this fills up, and possibly repeating and reallocating multiple times until there are no more characters to be read. You could implement it this way, but it's not worth the trouble. 500 bytes is not very much space nowadays. - Brian Bistd::stringwould automatically size itself to fit, so obviously it would be a lot easier to use. In general, the way you did it is about how well you can do it without knowing enough about the size of the input to be more precise. If you wanted to save overall space, you could fill your buffer, then find its size and make another array of exactly that size, copy your buffer to that array and then deallocate the buffer. - IllusiveBrianfailbitand start a new buffer if it is set.std::stringprobably does something like this. - Red Alertstd::stringand it'sreservemethod if you know output could be large. - zoska