PDA

Click to See Complete Forum and Search --> : Deleting characters from a string


Wynd
Dec 15th, 2001, 03:12 PM
I want to erase from a string all puctuation characters. This is my code so far:string input;
string bad = "!@#$%^&*()~`[]{}-=_+|\"\'\\<>,.?/ ";

cout << "Enter a string: ";
getline(cin, input, '\n');

for (int i = 0; i <= input.length(); i++)
for (int j = 0; j <= bad.length() - 1; j++)
if (input[i] == bad[j])
{
cout << "Bad character found: \"" << bad[j] << "\"" << endl;
input.erase(i, 1);
}

cout << input << endl;The problem is this: if I enter "he&&&llo" for example, it only erases two ampersands, and the result is "he&llo". How can I fix this?

parksie
Dec 15th, 2001, 05:00 PM
The problem is, when you use erase(...) you change the length of the string.#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
string input;
string bad = "!@#$%^&*()~`[]{}-=_+|\"'\\<>,.?/ ";

cout << "Enter a string: ";
getline(cin, input, '\n');

for(string::iterator i = input.begin(); i != input.end();) {
if(find(bad.begin(), bad.end(), *i) != bad.end()) {
// Was found
input.erase(i);
} else {
++i;
}
}

cout << input << endl;
}:)

Wynd
Dec 15th, 2001, 06:51 PM
Duh :)

What's an iterator?

kedaman
Dec 16th, 2001, 03:18 AM
An iterator is a a type that represents a pointer to a value in a container, by doing pointer aritmetics on the iterator, only (++ and in some cases -- )you will loop forward (or backwards) trough the iterator.

parksie
Dec 16th, 2001, 05:25 AM
Iterators are a core part of using C++ as you're supposed to. It's valid C++ to loop through using the indexing operator, but it's not moral in a lot of cases. And plus, then you can erase the specific iterator :)