Do I need to cast to unsigned char before calling toupper(), tolower(), et al.?

前端 未结 5 1203
广开言路
广开言路 2020-11-22 14:15

A while ago, someone with high reputation here on Stack Overflow wrote in a comment that it is necessary to cast a char-argument to unsigned char b

5条回答
  •  情书的邮戳
    2020-11-22 15:04

    In C, toupper (and many other functions) take ints even though you'd expect them to take chars. Additionally, char is signed on some platforms and unsigned on others.

    The advice to cast to unsigned char before calling toupper is correct for C. I don't think it's needed in C++, provided you pass it an int that's in range. I can't find anything specific to whether it's needed in C++.

    If you want to sidestep the issue, use the toupper defined in . It's a template, and takes any acceptable character type. You also have to pass it a std::locale. If you don't have any idea which locale to choose, use std::locale(""), which is supposed to be the user's preferred locale:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::string name("Bjarne Stroustrup");
        std::string uppercase;
    
        std::locale loc("");
    
        std::transform(name.begin(), name.end(), std::back_inserter(uppercase),
                       [&loc](char c) { return std::toupper(c, loc); });
    
        std::cout << name << '\n' << uppercase << '\n';
        return 0;
    }
    

提交回复
热议问题