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!
using the new[] operator
Quote:Original post by nuclear123
ok...well is it possible if so could someone give an example!
std::string answer;std::cin >> answer;
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.
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.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement