-2

In this problem I use C++. I have a for loop that uses string variable 'word' and should return this word in uppercase.

for(int i=0;i<word.size();i++){
            cout<<toupper(word[i]);
        }

However, instead of word itself it returns its ASCII code. And, when I write it this way, everything works fine

string a;
for(int i=0;i<word.size();i++){
            a=toupper(word[i]);
            cout<<a;
        }

I'm just curious why is that happening, why can't toupper() return string variables.

1 Answers1

3

The problem is that std::toupper returns an int, not a char.

You need to cast it:

std::cout << static_cast<char>(std::toupper(word[i]);

The reason that std::toupper (as well as std::tolower and all character classification functions) uses int instead of char is that they're inherited from C where int is used for all characters.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 4
    Side note: `toupper` also takes an `int`, not a `char`, and this can cause some weird and nigh-inscrutible errors if you pass it a `signed char`. See [the notes](https://en.cppreference.com/w/cpp/string/byte/toupper#Notes) in the previously linked documentation. – user4581301 Oct 27 '21 at 18:45
  • 1
    @user4581301: The issue is not that `toupper` takes an `int` but that it is specified to take an `unsigned char` value. It is the possibility of negative **values** that can cause problems, not the **type**. – Eric Postpischil Oct 27 '21 at 18:55
  • Regarding the part where you mentioned that C is using ìnt` for all characters, that's inaccurate. – Alaa Mahran Oct 27 '21 at 19:22
  • 1
    See [this answer](https://stackoverflow.com/a/45007070/12149471) to another question for more information on the background of why the cast to `unsigned char` is necessary, when passing arguments to functions declared in the `` header. – Andreas Wenzel Oct 27 '21 at 19:25
  • @AlaaMahran the wording could be better, but all of the character-testing and transforming utility functions in ctypes.h take `int` rather than `char`. – user4581301 Oct 27 '21 at 19:48
  • @AlaaMahran A `char` will be promoted to `int` almost all of the time. Even character literals like e.g. `'A'` will be an `int`. Also, since we have e.g. `EOF` which could have different values depending on if `char` is signed or not (which is implementation defined) it's almost always better to use `int` for single characters. Almost the only place where using `char` makes sense is in arrays (i.e. strings). – Some programmer dude Oct 28 '21 at 06:03