I'm trying to do an if statement inside a loop with an iterator over a string, but can't figure out how to get the current character for the if statement:
for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i) {
if (!isalpha(*i) && !isdigit(*i)) {
if(i != "-") { // obviously this is wrong
buffer.erase(i);
}
}
}
Can someone help me get the current character so I can do some additional if statements?
I can't figure out how to get the current character
You do it twice here:
if (!isalpha(*i) && !isdigit(*i))
When you dereference an iterator (*i
), you get the element to which it points.
"-"
This is a string literal, not a character. Character constants use single quotes, e.g., '-'
.
for (std::string::iterator i=buffer.end()-1; i>=buffer.begin(); --i)
This would be much simpler with reverse iterators:
for (std::string::reverse_iterator i = buffer.rbegin(); i != buffer.rend(); ++i)
if(i != "-")
should be
if(*i != '-')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With