Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reverse Token Output

Status
Not open for further replies.

donniea21

MIS
Feb 16, 2001
75
US
Here is what i have so far...this will take a users input string and take each word as a token and output on seperate lines. IE. "Hello" World outputs
Hello
World
I need to reverse this output ie
World
Hello

Here is my code:

#include <stdio.h>
#include <string.h>

int main ()
{
char string[100] = &quot; &quot;;
char *tokenPtr;

printf( &quot;Enter a line of text up to 100 character in length:\n&quot;);
gets(string);

printf(&quot;%s\n%s\n\n%s\n&quot;,
&quot;The String to be tokenized is:&quot;, string,
&quot;The Tokens are:&quot; );

tokenPtr = strtok( string, &quot; &quot; );

while ( tokenPtr != NULL ) {
printf( &quot;%s\n&quot;, tokenPtr );
tokenPtr = strtok( NULL, &quot; &quot; );
}

return 0;
}
 
Hi,

Here are some comments and suggestions:

>#include <stdio.h>
>#include <string.h>

>int main ()
>{
> char string[100] = &quot; &quot;;
> char *tokenPtr;

> printf( &quot;Enter a line of text up to 100 character in length:\n&quot;);
> gets(string);

Never use gets(), it's a bug waiting to happen. Use fgets instead. Also, note that the user should only be permitted 99 characters as you need to allow for the terminating null. You'll also want to check the return value before you try to tokenize the string.

if (NULL==fgets(string,sizeof string,stdin)) {
/* ERROR! */
} else {
/* find the newline in the string */
char *tmp=strchr(string,'\n');
if (tmp!=NULL) {
/* discard the newline */
*tmp=0;
}
/* Note: if tmp==NULL, this means the user entered more
* than 99 characters
*/
}

> printf(&quot;%s\n%s\n\n%s\n&quot;,
> &quot;The String to be tokenized is:&quot;, string,
> &quot;The Tokens are:&quot; );

> tokenPtr = strtok( string, &quot; &quot; );

> while ( tokenPtr != NULL ) {
> printf( &quot;%s\n&quot;, tokenPtr );
> tokenPtr = strtok( NULL, &quot; &quot; );
> }

Ok, good, but where's the reversing process? :) I guess this is where you're stuck. How about a simple array of pointers to store each token?

Above, declare:

/*** untested ***/

#define TOKEN_MAX 100 /* or some suitable number */

/* ... */

char *tokens[TOKEN_MAX];
size_t tokenCtr=0;

/* then down below */

tokenPtr = strtok( string, &quot; &quot; );

while ( tokenPtr != NULL ) {
if (tokenCtr<TOKEN_MAX) {
tokens[tokenCtr++]=tokenPtr;
} else {
/* handle error and exit loop */
}
tokenPtr = strtok( NULL, &quot; &quot; );
}

Then printing them out is simple:

while (tokenCtr>=0) {
printf(&quot;%s\n&quot;,tokens[--tokenCtr]);
}

HTH,

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top