-
Array Questions
O.K. say i have a char array but i do not know how many characters are going to be inputed from the user. Is there a way that i can declare an array and then edit how many places i need on the fly? Also say i declare an array say....char mychar[10]; ......but come to find out that for some reason i need to have an extra place for something. Is there a way that i can stuff something in it?
Thanks!
-
For the first one, use std::string. For a more general solution, a std::vector is a dynamic array.
-
A static array is static. No way to change its size.
You can use dynamic arrays with new[] but you'll have to watch the size of the array yourself. Also most input functions don't tell you when the user enters too much, which means that you have to read character by character.
Growable array classes like std::vector take the memory management away from you. However you still can't properly read in, unless you use instream iterators, which is a rather advanced C++ topic.
The std::string class finally does everything for you. Memory management, size watching and all the stuff that makes C so hard for newbies are all well hidden.
-
say just for a learning experience i wanted to make my own class that would create strings.
Could someone let me know how exactly the string class works. I mean how does it take a character and put it in memory and then how does it keep up w/ all the different characters and put them into a string.
I know that there is already a string.h file out there but say i wanted to create my own file for creating a string from characters. how would i need to go about it? WHere would i need to start?
-
A simple string class just allocates a character array via new[] and stores the characters there. It also stores its own length so that it doesn't need NUL-terminated strings.
Then it provides member functions and overloaded operators to manipulate the string, which make it grow and shrink as necessary.
std::string might have various optimizations: VC++7's implementation for example has a char[16] member to avoid heap allocations for very small strings.