Can not erase other non alphabet characters without going out of range

I'm supposed to get a string with spaces, numbers, or punctuations to become alphabet characters only. When I run the function it says I am out of range.
For example, if I input "dogs are fun.", it should become "dogsarefun". Any help greatly appreciated, thanks.

#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();


while (input[i]!=size){
if(isspace(input[i]) || isdigit(input[i]) || ispunct(input[i])){
input.erase(i);
}

else i++;
}
return input;

}

int main() {
string input;

cout << "Enter a string to test: ";
getline(cin, input);

cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
Last edited on
Please use code tags next time.

It doesn't crash, but it doesn't work...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input)
{
	int size;
	int i= 0;
	size = (int)input.size();
//	while (input[i]!=size)
	while (input[i] < size)
	{
		if(isspace(input[i]) || isdigit(input[i]) || ispunct(input[i]))
			{
			input.erase(i);
			}
		
		else i++;
	}
	return input;
}

int main()
{
string input;

cout << "Enter a string to test: ";
getline(cin, input);

cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
quincy, on line 14 (of SamuelAdam's formatted post), you are comparing a character to an integer. While this is perfectly legal in C++, it probably isn't doing what you think it's doing.
You probably mean to be doing
while (i < size)
Since you are erasing characters, you also probably want to update the size after an erasure.
I realized your while loop is not working.
I'm sure you can make it work but I have my own method.

1
2
3
4
5
6
7
8
9
10
11
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string inputStr)
{
string newString;
	for (int i =0; i <= inputStr.size(); i++)
	{
		if ((inputStr[i] >= 65 && inputStr[i] <= 90) || (inputStr[i] >= 97 && inputStr[i] <= 122)) 
			{newString=newString+inputStr[i];}
	}
return newString;
}
Last edited on
How do I include tags in my question?

Also, Samuel, where did you get those numbers from in your if statement: 65, 90, 97, 122
http://www.cplusplus.com/reference/cctype/isalpha/

If done from scratch:
- build, not erase
- range-based for loops

Or maybe consider one of the algorithms std::isalpha(), together with
http://www.cplusplus.com/reference/algorithm/copy_if/
or
http://www.cplusplus.com/reference/algorithm/remove_if/
Last edited on
Topic archived. No new replies allowed.