Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ string iterator

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?

like image 815
Joe Avatar asked Mar 24 '11 17:03

Joe


2 Answers

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)
like image 146
James McNellis Avatar answered Sep 30 '22 02:09

James McNellis


if(i != "-")

should be

if(*i != '-')
like image 31
Luzik Avatar answered Sep 30 '22 00:09

Luzik