|
-
Dec 15th, 2001, 04:12 PM
#1
Thread Starter
Fanatic Member
Deleting characters from a string
I want to erase from a string all puctuation characters. This is my code so far:
PHP Code:
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?
Alcohol & calculus don't mix.
Never drink & derive.
-
Dec 15th, 2001, 06:00 PM
#2
Monday Morning Lunatic
The problem is, when you use erase(...) you change the length of the string.
Code:
#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;
}
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Dec 15th, 2001, 07:51 PM
#3
Thread Starter
Fanatic Member
Duh 
What's an iterator?
Alcohol & calculus don't mix.
Never drink & derive.
-
Dec 16th, 2001, 04:18 AM
#4
transcendental analytic
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.
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
-
Dec 16th, 2001, 06:25 AM
#5
Monday Morning Lunatic
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
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|