Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...