Thread: General Code review

  1. #1
    Registered User
    Join Date
    Feb 2006

    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?

                                                    //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.
            while (r>0)
              printf("%s ",value[r-1]);
              fprintf(fo," ");
            fclose(fo);  // Closes output file pointer
    Thanks to all who comment,

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > Is there a better way to do this?
    There's always a different way

    Some comments
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Code Review
    By trillianjedi in forum Projects and Job Recruitment
    Replies: 3
    Last Post: 06-18-2008, 12:29 PM
  2. Code Review
    By Thantos in forum C Programming
    Replies: 8
    Last Post: 03-06-2004, 06:20 PM
  3. Code review: Bulletproof input
    By Brighteyes in forum C Programming
    Replies: 1
    Last Post: 03-30-2003, 08:31 PM
  4. Code review please
    By Brighteyes in forum C Programming
    Replies: 9
    Last Post: 03-29-2003, 06:28 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM