Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using toupper on char returns the ascii number of the char, not the character?

Tags:

c++

int main()
{

char hmm[1000];

cin.getline(hmm, 1000);
cout << hmm << endl;    //this was to test if I could assign my input to the array properly
for (int sayac = 0; hmm[sayac] != '@'; sayac++) {
    if (!isdigit(hmm[sayac])) {
        if (islower(hmm[sayac])) 
            cout << toupper(hmm[sayac]);
        else if (isupper(hmm[sayac]))
            cout << tolower(hmm[sayac]);
        else
            cout << hmm[sayac];
    }
}

"Write a program that reads keyboard input to the @ symbol and that echoes the input except for digits, converting each uppercase character to lowercase, and vice versa. (Don’t forget the cctype family.) "

I'm doing this exercise from the primer book. But when I run it, it returns the ascii order of the char, not the uppercase/lowercase version of the character. Couldn't figure out the problem. Can someone tell my why please?

(I may have other problems about the exercise, please don't correct them if I have. I want to fix it on my own (except the problem I explained), but I can't check the other ones as I have this problem.

like image 524
maltoshi Avatar asked Jan 29 '23 03:01

maltoshi


1 Answers

When writing

std::cout << toupper('a');

the following happen:

  1. int toupper(int ch) is called, and returns an integer whose value is 'A' (0x41).
  2. std::basic_ostream::operator<<(std::cout, 0x41) is called, that is the int (2) overload since an int was provided.

Overall, it prints "65".

As a solution, you can cast back your upper case to a char:

std::cout << static_cast<char>(toupper('a'));
like image 79
YSC Avatar answered Apr 27 '23 14:04

YSC