Remove spaces and punct from a string

I'm a beginner doing a homework assignment. If you answer, please just use hints.

I'm trying to remove all spaces and punctuation from a string. The code block below works if there is only one character to be removed. If there are two or more, it doesn't erase the correct character. I think this is because the string being tested no longer matches the string being edited. However, if I replace input with abbrInput in the if statement, I get a debug error during runtime. I think I'm close to getting this but can't see what might be wrong. Can this be made to work or do I have to approach it from a different direction?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  // for loop to strip out spaces and punctuation  (DOESN'T WORK!!)

	//This works if there is only one character to erase. If there are 
	//two or more, the string being edited no longer matches the string
	//being tested and the wrong character gets erased on the subsequent 
	//iterations. This results in isPal never being true.

		string abbrInput(input);  // work on a copy, not the original
		strLength = abbrInput.size();
		for(int i = 0; i < strLength; ++i)
		{
			if(ispunct(input.at(i)) || isspace(input.at(i)))
			{
				abbrInput.erase(i,1);
			}
		}


Thanks in advance,
Ken Long
Albuquerque
Instead of erasing elements from the original string, you could have a second, temporary string to which you push non-space/non-punctuation characters.
Well, that hint resulted in a solution! I reworked the code block so that the if was testing for isalpha(). If true, it appended the character at index i to abbrInput. After the for loop stepped all the way through the string, abbrInput contained only the alpha characters, no spaces or punctuation.

Thanks!
Topic archived. No new replies allowed.