[prog] simple c++ question

Sue Stones suzo at bigpond.net.au
Mon Jun 23 11:26:58 EST 2003


G'day Gene,

I am not far ahead of you in learing C++, so I am glad tohave someone else 
asking C++ questions on this list.  

On Mon, 23 Jun 2003 08:25 am, Laura OConnor wrote:
> void readText(char *text[])
> {
>    char tempText[50];
>    int j = 0;
>
>    cout <<"Please enter a line of text";
>    cin.getline(tempText, 50)

You are reading strings into tempText, that is good, the name shows you have 
thought about this.

>    text[j] = strtok(tempText, " ");

strtok searches for the first token in Temp, overwrites the space with a Numm 
'\0' and then returns a pointer to the beging of that token, whilst it keeps 
track of where it is up to.  Each successive call to strtok returns a pointer 
to the next token in Temp.

The important thing that you have missed here is that these tokens are *still* 
part of Temp.  So once you leave the function readText wich is the scope of 
the variable Text it is destroyed, alond with teh datat hat was in it.

To solve this you need to add change the line like this
	char * temp2 = strtok(tempText, " ");  // grab the token so we can do things
									// with it
	text[j] = new (strlen(temp2) +1);  // get some space that wont be destroyed 			
								//when we leave the function
 	strcpy(strtok(text[j], temp2));		// note I generally get the arguments to
								// strcpy in the wrong order

>         //text[j] = "foo";    - this would work
>        //removed while loop to get rest of tokens for simplicity
> }
>
> int main()
> {
>    char *words[100];
>    readText(words);
>    cout << words[0];  //check the first element
>
>   return 0;
> }


If there are still things you don't understand please ask again.  I am sure 
that some more experienced C++ programmers will correct anything that I may 
have not quite right.

sue


More information about the Programming mailing list