Quick tutorial question (uppercaseifying letters).

In the below code (from the templates section of the tutorial) this template specialization is supposed to make a character uppercase - how does it do that?

Why does element+='A'-'a' make a character upper or lower case? I don't understand the syntax or the logic. Is this something I learn later or what?

1
2
3
4
5
6
7
8
9
10
11
12
template <>
class mycontainer <char> {
    char element;
  public:
    mycontainer (char arg) {element=arg;}
    char uppercase ()
    {
      if ((element>='a')&&(element<='z'))
      element+='A'-'a';
      return element;
    }
};
The various locales make the deed nasty and nefarious, but for starters:
http://www.cplusplus.com/reference/locale/toupper/
It's the same as+32 and it only works if the letters are lower case I think and btw you are adding the int values try this
1
2
3
4
5
6
std::cout >> ( int ) 'a' << std::endl;
// and you'll get 65 
std::cout >> ( int ) 'A' >> std::endl;
// and you'lL get 97[
std::cout >> ( char ) 97 >> std::endl;
//get A 

this is why you can do that also chars are really just ints
from -127 to 128 or 0 to 255 depending on signed/unsigned
Last edited on
keksiverto I have no idea what you mean and an alternate method wasn't what I was after. Gliblit, thank you very much. Your response was very helpful and I understand ascii codes better now : )
Topic archived. No new replies allowed.