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:
What am I doing wrong with the tolower
function that's making it return 116 instead of 't' when I call tolower('T')
Are there better ways to convert a string to lowercase in C++ other than using tolower
on each individual character?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With