General Code review
I am a student learning C and would like some opinions on the follow section of my program. The below section uses STRTOK to read in a string, break it into tokens and finally print to stdout and to file the tokens in the reverse order in which they were read. For the sake of space, I have included only the section that pertains to the STRTOK function. Though the program works, the method in which I reverse the text has me wondering if there is a more effecient way. Basically, I write the contents of each token to a pointer location, and then printf the newly created pointer.
Is there a better way to do this?
Thanks to all who comment,
//reverse string section
printf("\n\nThe sentence printed in reverse order is: ");
tkptr = strtok(originalString, seps);
while(tkptr != NULL)
tkarray[r++] = originalString;
tkptr = strtok(NULL,seps);
fo=fopen("proj_out.txt","w"); //Opens file for writing.
//iterates through tokens displaying the sentence in reverse and writes out tokens to file.
fclose(fo); // Closes output file pointer
> Is there a better way to do this?
There's always a different way ;)
1. strtok() modifies your string, which could be a really bad idea in some cases.
2. you also need to declare an array in advance with the maximum number of words in your string.
Here's an alternative suggestion.
Use a loop to walk backwards over the string, and write out each word as you find it.