I just came across an example of this happening in my code...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int main()
{
string input;
char *p;
stack<double> RPN_stack;
int c;
double a, b, n;
cout << "Enter RPN string: ";
getline( cin, input );
p = new char[ input.size() + 1 ];
strcpy( p, input.c_str() );
p = strtok( p, " " );
while ( p ) {
//rest of program
p = strtok( NULL, " " );
|
Once I create the new char array and then break it up with strtok, I think I can only access the first token of that original string that was put into *p. So, I think I can only delete and reclaim that first token, not the entire string first copied into p.
1) Am I right in thinking there is a loss of memory due to the string tokens I can no longer access after strtok()?
2) If so, is there a way to delete that entire char array?
3) The overall goal of this code segment is to read in a variable size input string from cin, divide up that input into tokens, and analyze the tokens for use later in the program. I've found that strtok can only take a non-const char*, but I seem to only be able to get a string object to convert into a const char* via string::c_str(). So I work around it with the pointer p and allocating a new char array based on string, essentially creating a second copy of the input. I suspect this isn't the most efficient way to do things. Any better solution to this problem?
By the way, I'm teaching myself C++ for fun from a library book I found (C++ Without Fear), so forgive me if I'm missing something obvious.