Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

iBookG4user

macrumors 604
Original poster
Jun 27, 2006
6,595
2
Seattle, WA
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
 
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)
 
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.

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: the only character to be stripped is space. Every character that's not a space is allowed. You should only express the relationship "a character that's not a space". Neither more nor less.

Third, itit 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.


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

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

Once you have an in-place space-stripping function, it becaomes 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 spaces, and your choice of function name: stripWhite. 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)

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

Attachments

  • Screen shot 2009-10-04 at 11.43.04 PM.png
    Screen shot 2009-10-04 at 11.43.04 PM.png
    142.6 KB · Views: 103
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 :)
 
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
 
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.

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.
 
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!



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.

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.
 
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;
}
 
Code:
 if ( (' ' == ch) || ('\t' == ch) )

Consider using the <ctype.h> function/macro isspace(). It detects more whitespace chars.

man 3 isspace
 
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>
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.