Convert a single character to lowercase in C++ - tolower is returning an integer
116 is indeed the correct value, however this is simply an issue of how std::cout
handles integers, use char(tolower(c))
to achieve your desired results
std::cout << char(tolower('T')); // print it like this
It's even weirder than that - it takes an int
and returns an int
. See http://en.cppreference.com/w/cpp/string/byte/tolower.
You need to ensure the value you pass it is representable as an unsigned char
- no negative values allowed, even if char
is signed.
So you might end up with something like this:
char c = static_cast<char>(tolower(static_cast<unsigned char>('T')));
Ugly isn't it? But in any case converting one character at a time is very limiting. Try converting 'ß' to upper case, for example.
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.