Sign in to follow this  
nuclear123

using the new[] operator

Recommended Posts

cout << "Enter a string" << end;
cin >> <---- i want to use new to allocate as many character bytes at the string's size how would i do this?


for example if string is "hello" i want to use the new operator to store dynamically 6 bytes for this string...and then store each byte in this string so i can manipulate it :) -thx for help/direction

i understand i need to use the new[] operator...i'm just unsure how to use it for the situation as for i don't use it much!

Share this post


Link to post
Share on other sites
Also, it sounds like youre wanting to manipulate individual characters.

in the example above, you can use theString.length() to get the length in characters or to address an individual character use theString[n] where n is the character number you want to access, between 0 and length() - 1.

Share this post


Link to post
Share on other sites
You cannot know the length of the string in advance. You can make a buffer of some size to start, and read characters until it fills up. At that point, you allocate a larger one (say twice the size), copy the contents of the old one, delete the old one and keep going.

So you basically need an object that has:
* a `char *' where the data is stored,
* an integer indicating the length of the string, and
* an integer indicating the size of the buffer currently allocated.

You can then make a method to append a character, which will regrow the buffer if needed. Finally you'll make a function that reads characters from a stream and appends them to this object.

Or you can use std::string which already implements precisely this.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this