C++ String Loop – How to Convert to Lowercase

c++string

I know there were a couple of other questions on this from a while back, but I looked over those and still couldn't figure it out. I'm trying to take user input in the form of a string, then loop through that string converting all of the uppercase to lowercase so that I can display it all in lowercase.
Where am I going wrong?

int main()
{
    cout << "Enter Text: ";
    string Text;
    getline(cin, Text);
    for(int i=0; i<Text.length(); i++)
    {
        if(islower(Text[i]) == false)
        {
            tolower(Text[i]);
            i++;
        }
        Text[i] = Text[i];
    }
    cout << "Your text is: ";
    cout << Text;
    cout << "\n";
}

I'm very new to C++ and I'd be lying if I said I had much of an idea even where I was going wrong. Line 11, where the for loop is says that it's trying to compare two different signs, but I don't know what that means or if that's the source of my problem. Line 15 where the tolower() is says that it's 'ignoring return value of function declared with pure attribute' but I still don't know what that means either.
Please help.

Best Answer

A few points:

  • tolower returns the lowercase character if it exists ('A' becomes 'a', 'a' is unchanged, '9' is unchanged, etc.)
  • The line Text[i] = Text[i]; does not do anything, you want Text[i] = tolower(Text[i]);
  • There is no need to check if each character is lowercase, tolower will handle that for you

Simplified:

#include <iostream>

using namespace std;

int main() {
    cout << "Enter Text: ";
    string Text; 
    getline(cin, Text);
    for (int i = 0; i < Text.length(); i++)
        Text[i] = tolower(Text[i]);
    cout << "Your text is: ";
    cout << Text;
    cout << "\n";
}
Related Question