Thread: String formatting

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    4

    String formatting

    Hey guys
    So I'm trying to write a program that behaves as follows:

    1. Define a word as any sequence of characters delimited by whitespace.

    2. If the first character of a word were to be printed beyond the
    first 72 columns, then delete the trailing whitespace characters of
    x2, append '\n' to the end of x2, and then continue by appending that
    word and the following characters to x2.

    3. The C character '\n' represents a newline. After the newline,
    consider the next character as appearing in the first column.
    Continue to copy from x1 to x2, while keeping track of the current
    column. When we go beyond the first 72 columns, then again execute
    rule 2 above.

    This is what I've been able to come up with:

    Code:
    #include <stdio.h>
    
    main()
    {
      char x1[500] = "The quick brown fox jumped over the lazy dog.  Now is"
    	         " the time for all good men to come to the aid of their"
    		 " country.  We need another good and long sentence"
    		 " to fill out this paragraph.  By making this paragraph"
    		 " longer, we will have a chance to insert lots of"
                     " newline characters.";
      char x2[500], tmpArr[500];
      int i, colCount, counter, curWordLength, atStartWord, offset, wasSpace, numSpacesToBeCleared;
    
      colCount = i =counter = curWordLength = offset = wasSpace = numSpacesToBeCleared = 0;
      atStartWord = 1;
    
      /* While we are not on the last char.. */
      while (x1[counter] != '\0'){
    
        /* Check if a new word is starting */
        if (wasSpace == 1){
          if (x1[counter] != ' ' && x1[counter] != '\t'){
            atStartWord = 1;
            wasSpace = 0;
          }
        }
    
        if(atStartWord == 1){
          curWordLength = getWordLength(x1[500], colCount);
          
          /* Word goes over 72, wrap it over HERE */
          if(colCount + curWordLength >= 72){
    
            /* Here we need to clear all the spaces at the end of the current line */
            numSpacesToBeCleared = numBlankSpacesToKill(x2, counter);
    
            while (i <= counter-numSpacesToBeCleared){
              tmpArr[i] = x2[i];
              i++;
            }
            x2[500] = tmpArr[500];
            
    	counter -= numSpacesToBeCleared;
            offset += numSpacesToBeCleared;
    
            x2[counter+offset] = '\n'; 
            colCount = 0;
          }
    
          /* Else start copying it */
          else{
            x2[counter+offset] = x1[counter];
          }
    
          atStartWord = 0;
        }
    
        else{
          
          x2[counter+offset] = x1[counter];
    
          /* If this character is a space or a tab, set wasSpace to true */
          if(x1[counter] == ' ' || x1[counter] == '\t'){
            wasSpace = 1;
          } 
        }
    
        counter++;
    
      }
    
      printf("%d", x2);
    
    }
    
    
    /* Helper method 
    To determine the length of a word from a given starting point*/
    int getWordLength(char arr[500], int start)
    {
    
      int counter, wordLength;
      counter = wordLength = 0;
    
      while (arr[start] != ' ' && arr[start] != '\t'){
    
        wordLength = wordLength + 1;
        start = start + 1;
    
      }
    
      return wordLength;
    
    }
    
    
    /* Helper method
    To remove all the white spaces from the end of an array */
    int numBlankSpacesToKill(char arr[500], int start){
    
      int numWhiteSpaces;
      numWhiteSpaces = 0;
    
      while (arr[start] == ' ' || arr[start] == '\t'){
        start--;
        numWhiteSpaces++;
      }
    
      return numWhiteSpaces;
    }
    Running this on unix, I'm hitting a 'Segmentation fault' and having written this in only notepad and emacs/gcc these generic errors are driving me nuts..
    Any ideas?

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Post your error code. Or, send me a six pack and I'll do a code review.
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    4
    Error code? Right now all I'm getting when I enter the command './a.out' is "Segmentation fault", is there a way to get the error code from there?

  4. #4
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    State clearly what you're trying to do in a nutshell??

    For starters come up with a sound algorithm for solving this before diving into the C
    Copying string in x1[] to x2[] and wrapping around ie installing a newline in x2[], after the 72nd column??

    Remove whitespace chars by moving the x1[] offset while holding the x2[] offset until a non-whitespace char appears.

  5. #5
    Registered User
    Join Date
    Oct 2009
    Posts
    4
    Sorry, should have posted the objective.
    The goal here is to wrap around every 72nd column, never breaking up a word. So if a word is going to go past the 72nd column, it should wrap around AND all the spaces at the end of the line (pre-wrap-around) should be removed. Then '\n' should be appended, and the program continues on.
    The offset was a var declared by me as a way of tracking the difference in the current position in arrays x1 and x2.
    Hope that was clear.

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    At a glance (there may be more)
    #1
    Code:
    char x1[500] = "The quick brown fox jumped over the lazy dog.  Now is"
    
    ...
    
    if(atStartWord == 1){
        curWordLength = getWordLength(x1[500], colCount);
    
    ...
    
    int getWordLength(char arr[500], int start)
    {
    x1 is an array of 500 characters with a valid index in the range of 0 to 499. When you call the function, you are passing x1[500] which is an invalid index and a character to a function which looks like it's expecting an array/pointer.


    #2
    Code:
    char x2[500], tmpArr[500];
    
    x2[500] = tmpArr[500];
    Another instance of using invalid indexes with your arrays.



    #3
    Code:
    if(atStartWord == 1){
        curWordLength = getWordLength(x1[500], colCount);
          
        /* Word goes over 72, wrap it over HERE */
        if(colCount + curWordLength >= 72){
    The objective seems to be (as stated by you) to wrap if the start of a word is at (or more than) the 72nd column, not if the length of the word plus whatever column we happen to be at is more than 72. That is, if we are at the start of the word and the column count is already more than 72 then we should do the whole erase whitespace and append a newline and continue thing (the length of the word has no bearing and the getWordLength function would seem to then be pointless).


    #4
    Code:
    printf("%d", x2);
    x2 is a character array and not an integer. %d is for integers, %s is for strings.



    #5
    You are not updating your colCount variable anywhere in your code. You initialize it to 0, and then later have a reset back to 0 but I don't see anywhere where you actually increment it.


    #6
    You are not properly null terminating x2 prior to printing.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    100 ways things to solve your segmentation faults
    (I should make this a book. It shoud become a best seller)

    1. Use a debugger and spot exactly where the program crashes
    2. Use printf("Nope, doesn't crash here\n")
    3. Use a debugger and spot exactly where the program crashes
    4. Use printf("Nope, doesn't crash here\n")
    ....
    99. Use a debugger and spot exactly where the program crashes
    100. Use printf("Nope, doesn't crash here\n")

  8. #8
    Registered User
    Join Date
    Oct 2009
    Posts
    4
    Thanks for the great points guys, went through the code as you said.
    I've got it working now, printing out the final string in the format it should.
    Thanks again!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM