0

I am writing a program that asks for input of letters and and sorts them the letter and occurrence based on input. I'm at the end of my code and I am trying to convert the uppercase letters to lowercase. I'm trying to do this:

cout << tolower(char('A'+i)) << " " << alphabets[i] <<endl;

But the tolower() outputs a number instead of the lowercase version of the letter? Like for example, input "aaaa" gives me :

97 4

and input "bbbbb" gives me:

98 5

But when I take out the tolower, input like "aaa" will be:

A 3

I don't understand why this is happening.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Sam
  • 31
  • 1
  • 6
  • 2
    `tolower` returns `int`. Cast it to a `char` if you want to print the character. – T.C. May 12 '15 at 05:50
  • "so I don't wanna post the whole code incase someone tries to copy it" -> but copying our answers is ok then? Seriously: Read [`man 3 tolower`](http://linux.die.net/man/3/tolower) – Nidhoegger May 12 '15 at 05:51
  • Giving ascii value of character. You can convert it again to char using char mychar = intvalueReturned – Pawan May 12 '15 at 05:52
  • One other minor concern in your code - beyond your question - is that `'A'+i` does not necessarily produce an uppercase alphabetic character. For ASCII and related character sets, it does. Other character sets do exist for which it does not. There is no guarantee that letters (whether uppercase or lowercase) are a contiguous set of values - there can be other characters between `'A'` and `'Z'`. – Peter May 12 '15 at 07:39

3 Answers3

5

tolower is an ancient function inherited from 1970's-era C, before function signatures reliably existed and before people really cared about different integer types for expressions.

So, it ignores types and returns a character in an int. Three alternatives:

  1. Cast: static_cast< char >( std::tolower( 'A' + i ) ).
  2. Use a variable: char lower = std::tolower( 'A' + i );
  3. Use a newer overload: std::tolower( 'A', std::locale() ).
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
1

tolower both accepts and returns an int, and std::cout cannot know that the int returned represents a char value. You can fix this by converting to char:

cout << static_cast<unsigned char>(tolower(char('A'+i))) 
     << " " << alphabets[i] << endl;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

A simple typecasting would solve this issue. For example:

char letter = 'J';
cout << char(tolower(letter)) << endl;
David Buck
  • 3,752
  • 35
  • 31
  • 35