c++stringcharlowercasetolower

Convert a single character to lowercase in C++ - tolower is returning an integer


I'm trying to convert a string to lowercase, and am treating it as a char* and iterating through each index. The problem is that the tolower function I read about online is not actually converting a char to lowercase: it's taking char as input and returning an integer.

cout << tolower('T') << endl;

prints 116 to the console when it should be printing T.

Is there a better way for me to convert a string to lowercase? I've looked around online, and most sources say to "use tolower and iterate through the char array", which doesn't seem to be working for me.

So my two questions are:

  1. What am I doing wrong with the tolower function that's making it return 116 instead of 't' when I call tolower('T')

  2. Are there better ways to convert a string to lowercase in C++ other than using tolower on each individual character?


Solution

  • That's because there are two different tolower functions. The one that you're using is this one, which returns an int. That's why it's printing 116. That's the ASCII value of 't'. If you want to print a char, you can just cast it back to a char.

    Alternatively, you could use this one, which actually returns the type you would expect it to return:

    std::cout << std::tolower('T', std::locale()); // prints t
    

    In response to your second question:

    Are there better ways to convert a string to lowercase in C++ other than using tolower on each individual character?

    Nope.