Search code examples
c++stlforeachg++stl-algorithm

Using for_each with tolower()


I am trying to use the STL function for_each to convert a string into lower case and I have no idea what I am doing wrong. Here's the for_each line in question:

clean = for_each(temp.begin(), temp.end(), low);

Where temp is a string that is holding a string. And here's the function that I wrote for low:

void low(char& x)
{
x = tolower(x);
}

And the compiler error that I keep getting is as such:

error: invalid conversion from void (*)(char&) to char [-fpermissive]

What am I doing wrong?

EDIT: Here is the whole function that I am writing:

void clean_entry (const string& orig, string& clean)
{
string temp;
int beginit, endit;

beginit = find_if(orig.begin(), orig.end(), alnum) - orig.begin();
endit = find_if(orig.begin()+beginit, orig.end(), notalnum) - orig.begin();

temp = orig.substr(beginit, endit - beginit);

clean = for_each(temp.begin(), temp.end(), low);
}

Solution

  • for_each's return-value is the function that you passed it — in this case, low. So this:

    clean = for_each(temp.begin(), temp.end(), low);
    

    is equivalent to this:

    for_each(temp.begin(), temp.end(), low);
    clean = low;
    

    when what you really want is probably this:

    for_each(temp.begin(), temp.end(), low); // note: modifies temp
    clean = temp;
    

    (or you can just eliminate temp to begin with, and use clean throughout).