Using pointers to strip spaces

Discussion in 'Mac Programming' started by iBookG4user, Oct 4, 2009.

  1. macrumors 604

    iBookG4user

    Joined:
    Jun 27, 2006
    Location:
    Seattle, WA
    #1
    Hello, I'm sorry to bug everyone again, but I've just been so overloaded with classwork and tests, I need a bit of help with the final C++ assignment. (Seriously, taking 20 units is not fun! I have 3 midterms this week, a speech and a research paper due, I don't have as much time as I need to do everything!) For this, the professor wants us to do the following "Using pointers write a function called stripWhite that will strip all of the white spaces from an array of characters. Your function should return the number of white spaces that you deleted."

    He said that we could use strings, although he has not said much at all about strings, so I don't have a good knowledge of them. (Nor has he said much about pointers... He really doesn't explain things well.) Thus I am using character arrays. Any help would be greatly appreciated, I know I must be a bother, but I can't thank you enough for all the help that you guys have given!

    Code:
    #include <iostream>
    using namespace std;
    
    void print(char sentence2[],int size);//function to print sentence when done
    
    void stripWhite(char point[],char sentence2[],int size);//uses pointers to strip sentence of spaces
    
    int main ()
    {//main
    	
    	char sentence1[1000];//first array to obtain sentence
    	
    	int size;//integer to decide how big new array should be
    	
    	cout << "Please enter a sentence and I will strip it of all spaces." << endl;
    	
    	cin >> sentence1;//input for first array
    	
    	for(int i=0;i<1000;i++)//for loop to find out size of array
    	{//for
    		if(sentence1[i] >= 'a' && sentence1[i] <= 'z' || sentence1[i] == ' ' || sentence1[i] == ',' || sentence1[i] == '.')
    		{//if
    			size++;
    		}//if
    	}//for
    	
    	char sentence2[size];//new array with exact size it should be
    	
    	for(int y;y<size;y++)//for loop to copy contents of first array to second
    	{//for
    		sentence2[y]=sentence1[y];
    	}//for
    	
    	char point;//soon to be pointer
    	
    	for(int y;y<size;y++)//for loop to get point to become a pointer to second array
    	{//for
    		point[y]=&sentence2[y];
    	}//for
    	
    	cout << endl;
    	
    	stripWhite(sentence2,point,size);
    	
    	return 0;
    }//main
    
    void print(char sentence2[],int size)//print function
    {//void print
    	
    	for(int z;z<size;z++)
    	{//for
    		cout << sentence2[z];
    	}//for
    	
    }//void
    
    char stripWhite(char point[],char sentence2[],int size)//function to strip sentence of spaces
    {//char stripWhite
    	
    	for(int y;y<size;y++)//for loop to only set non space characters to second array
    	{//for
    		if(point[y]!=' ')//if to decide if it is a space or not
    		{//if
    			sentence2[y]=*point[y];
    		}//if
    	}//for
    
    	print(sentence2,size);//function call to print finished sentence
    	
    }//char
    
     
  2. macrumors 603

    Joined:
    Aug 9, 2009
    #2
    You have some studying to do. If you're supposed to understand pointers by now, then you're very far behind where you should be. Depending on when the deadline for the final assignment is, it may be possible to remedy this, or it may not.

    First, you're not using pointers, so if this were handed in to me, I'd have to give you an F.

    Second, you're missing some important things, like the letters 'A'-'Z', punctuation like parentheses, colon, etc. In effect, you're trying to define a set of unstripped characters, when the assignment is much simpler than that: strip only the whitespace. Every character that isn't whitespace is allowed. You should only express the relationship "a character that isn't whitespace". Neither more nor less.

    Third, it seems pretty clear that you haven't tried actually compiling the code you posted. Or if you have tried, you haven't mentioned the error messages you've gotten. For example, the following is definitely an error:

    Code:
    char point;//soon to be pointer
    ...
    point[y]=&sentence2[y];
    
    Sorry to say, but 'point' is not a pointer, nor is it soon to be a pointer. It is a single character. Subscripting it as 'point[y]' is syntactically meaningless.

    Also, you have some serious bugs in your handling of your char arrays as string buffers. It appears as if you don't understand the C convention of nul-terminated strings.

    http://en.wikipedia.org/wiki/C_string


    I recommend a different approach. Write the heart of the assignment first: the function that strips whitespace and returns a count. For example, it should conform to this declaration:

    Code:
    int stripWhite( char *strBuffer );
    
    You should assume that strBuffer points to a nul-terminated C-style string. You should also assume that the stripping of whitespace should occur in-place, and the buffer on return holds a nul-terminated string with all whitespace stripped out. The returned int is the count of whitespace chars stripped.

    Once you have an in-place whitespace-stripping function, it becomes simple to write a version that strips a copy of the original string. Simply copy the original string to another buffer of suitable size, and strip the copy in-place.


    Note: there is an inconsistency in what you say the assignment is, stripping whitespace, and what your code appears to operate on. Whitespace consists of more characters than just space. For example, it includes tab, newline, form-feed, and possibly others, depending on context. If the assignment is really "strip whitespace", then that's quite different from "strip spaces".

    http://en.wikipedia.org/wiki/Whitespace_(computer_science)
     
  3. thread starter macrumors 604

    iBookG4user

    Joined:
    Jun 27, 2006
    Location:
    Seattle, WA
    #3
    First, the professor just introduced pointers last class period and he expects us to write the program for the following class period. Second, you could be just a hair nicer about your approach, this is a new and foreign language to me and I have 5 other classes that I have to complete at the same time. If I had the time to study C++ then believe me I would spend many more hours on it than I can right now. And third, the function name stripWhite was given by the teacher as the name that we have to use for said function.

    Yes, I was getting compile errors, I'm uploading a screenshot of them now...
     

    Attached Files:

  4. macrumors regular

    Joined:
    Nov 24, 2006
    Location:
    The Netherlands
    #4
    Been ages since I wrote straight C, but I'd probably do it something like this (if I remember correctly (which I probably don't) )

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int stripSpaces(char *, char *);
    
    char sentence1[] = "Hello world, th is is a sma ll test.        ";
    
    int main (char *argv[],int argc) {
    
     char *result      = (char*) malloc(sizeof(char) * strlen(sentence1));
     int charsStripped = stripSpaces(sentence1, result);
    
     printf("Result: %s (%d chars stripped)\n",result, charsStripped);
     if (result) free(result);
     return 0;
    };
    
    int stripSpaces(char *input, char *result) {
     char *resultPointer = result;
     char *pointer       = input;
    
     while (*pointer) {
      if (*pointer!=' ' && *pointer!='\t') {
       *(resultPointer++) = *pointer;
      };
      pointer++;
     };
     *resultPointer = '\0';
    
     return(strlen(input) - strlen(result));
    };
    
    And yes, this is probably (if it's correct) doing your homework for you, but when you can explain this to your teacher you'll have learned something anyways :)
     
  5. macrumors 6502

    Joined:
    Apr 24, 2008
    #5
    How about this approach:

    You allocate a buffer which is "large enough" for your destination string. "Large enough" in this case would be "as large as your original string", since it can only get smaller.

    Set up two pointers. One to the start of the original, the other to the start of the destination.

    For each character in the original, check whether it's a whitespace character (note: like chown33 said, that's not just spaces). If so, advance the source pointer by one, but not the destination pointer. You've just skipped a whitespace, so increment your tally.

    If it's not a whitespace, copy the character over to the destination buffer and increment both pointers.

    Hope that helps,
    Sander
     
  6. macrumors 603

    Joined:
    Aug 9, 2009
    #6
    First, you didn't say that pointers had just been introduced. Since you didn't use pointers in your code, though, I still think it gets an F. Second, if you're overloaded, then you're taking too many classes at once. If you don't have the time to study adequately, then you shouldn't expect to pass. That may be harsh, but that's reality. Third, if I give you a function-name that doesn't match the assignment, you are free to change it to match the assignment. Changing a function-name is the least of your problems.

    This may all seem brutal and harsh, but if you're consistently unable to complete assignments without having other people assist you or flat out do the work for you, then I don't think you should pass the class, because you don't know the material and aren't doing the work.
     
  7. macrumors newbie

    Joined:
    Oct 5, 2009
    #7
    From looking at your code, it appears you may be over thinking this. I would create an array and use
    cin.getline(your-char-array, sizeofarray) ;

    (its been awhile, but I don't recall you being able to input spaces with just cin >> variable; )

    ex:

    char getWhiteSpaceArray[50];
    cin.getline(getWhiteSpaceArray, 50);

    Next, you need to pass your array to your "stripWhite" function:

    stripWhite(getWhiteSpaceArray);

    You are now going to use a pointer when you create and code your function.

    void stripWhite(char *yourString)
    {
    }

    The * operator specifies that you are now "pointing" to your getWhiteSpaceArray array. Any changes you make to *yourString in this function will affect the original array without returning anything. I am assuming this is how your professor wants you to use pointers.

    Now to actually strip out the white space. Hopefully you would be able to figure this part out, as it doesn't require the use of pointers, but I will show you what I would do.

    Have a for loop go through and find white space for you. If it finds white space, remove it like so:

    for(int count = 0; count < (size of string); count++)
    {
    if(yourString[count] == ' ') //(' ' is space between)
    yourString[count] -= 1;
    }

    If you have coded correctly, you can output the user entered string and it will print with no spaces. I just did this and it worked fine. Hope this helps!



    Fail post is fail. Your opinions on people's study habits and ability to complete classes and homework are unnecessary and unwanted. Learning to code is difficult for some people and sometimes requires explanation from multiple sources. Help out or shut up.
     
  8. macrumors 603

    Joined:
    Aug 9, 2009
    #8
    That doesn't strip whitespace. It converts space (0x20) to Unit Separator (0x1F).
     
  9. macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #9
    Assuming this story is true, given the limited exposure to concepts required and time remaining for final exams I feel a useful working example would be more beneficial toward passing finals than the concern of providing finished homework.

    So ...

    Code:
    /* =============================================================================
     * File - main.cpp
     * -----------------------------------------------------------------------------
     * Using pointers to strip spaces
     * 
     * Hello, I'm sorry to bug everyone again, but I've just been so overloaded with
     * classwork and tests, I need a bit of help with the final C++ assignment.
     * (Seriously, taking 20 units is not fun! I have 3 midterms this week, a speech
     * and a research paper due, I don't have as much time as I need to do
     * everything!) For this, the professor wants us to do the following
     * 
     *  "Using pointers write a function called stripWhite that will strip all of
     *   the white spaces from an array of characters. Your function should return
     *   the number ofwhite spaces that you deleted."
     * 
     * He said that we could use strings, although he has not said much at all about
     * strings, so I don't have a good knowledge of them. (Nor has he said much
     * about pointers... He really doesn't explain things well.) Thus I am using
     * character arrays. Any help would be greatly appreciated, I know I must be a
     * bother, but I can't thank you enough for all the help that you guys have
     * given!
     */
    
    #include <iostream>
    #include <string>
    
    int stripWhite(char* pSrc)
    {
        int     count   = 0;
        char*   pDst    = pSrc;
        char    ch;
        while ( ch = *pSrc++ ) {
            if ( (' ' == ch) || ('\t' == ch) ) {
                count++;
                continue;
            }
    
            *pDst++ = ch;
        }
    
        *pDst = 0;
    
        return count;
    }
    
    
    int main()
    {
        std::cout << "Enter a sentence and I will strip it of all white space.";
        std::cout << std::endl;
    
        std::string str;
        std::getline(std::cin, str);
    
        char    buff[str.length() + 1];
        memset(buff, 0, str.length() + 1);
        strcpy(buff, str.c_str());
    
        int     ws;
        ws = stripWhite(buff);
    
        std::string strResult(buff);
        std::cout << strResult << std::endl;
    
        return 0;
    }
    
     
  10. macrumors 603

    Joined:
    Aug 9, 2009
    #10
    Code:
     if ( (' ' == ch) || ('\t' == ch) ) 
    
    Consider using the <ctype.h> function/macro isspace(). It detects more whitespace chars.

    man 3 isspace
     
  11. macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #11
    Certainly we could but it's often a difficult decision as to how much library stuff to use for the experience level of the person asking the question.

    I decided to show an implementation of 'stripWhite' in straight forward simple code as that's what seemed to be the focus of the question.

    We can do much more compact solutions for many of the questions asked here but it can sometimes hinder the understanding of the solution.

    Then again, being this is C++, that'd be <cctype>
     
  12. macrumors 603

    Joined:
    Aug 9, 2009
    #12
    I understand trying to simplify code for the inexperienced. My main point in using isspace() was that there are more whitespace characters than space and tab. It's unclear from the OP whether students are expected to know this or not. Any use of the term I'm familiar with considers VT, FF, CR, LF to be whitespace along with HT and SP.
     

Share This Page