How to Convert a C++ String to Uppercase

前端 未结 6 1740
不知归路
不知归路 2021-02-01 05:34

I need to convert a string in C++ to full upper case. I\'ve been searching for a while and found one way to do it:

#include 
#include 

        
6条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 06:15

    You need to put a double colon before toupper:

    transform(input.begin(), input.end(), input.begin(), ::toupper);
    

    Explanation:

    There are two different toupper functions:

    1. toupper in the global namespace (accessed with ::toupper), which comes from C.

    2. toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast(&std::toupper)

    Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.

提交回复
热议问题