Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 290
user83676 Avatar asked Nov 21 '15 23:11

user83676


3 Answers

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.

like image 131
Barry Avatar answered Nov 08 '22 17:11

Barry


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
like image 24
user4578093 Avatar answered Nov 08 '22 16:11

user4578093


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.

like image 2
Alan Stokes Avatar answered Nov 08 '22 16:11

Alan Stokes