How to Convert a C++ String to Uppercase

Thomas W. picture Thomas W. · May 2, 2014 · Viewed 90.4k times · Source

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 <iostream>
#include <algorithm> 
#include <string>  

using namespace std;

int main()
{
    string input;
    cin >> input;

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

    cout << input;
    return 0;
}

Unfortunately this did not work and I received this error message:

no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,

I've tried other methods that also did not work. This was the closest to working.

So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.

I got most of my info here: http://www.cplusplus.com/forum/beginner/75634/ (last two posts)

Answer

leemes picture leemes · May 2, 2014

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<int (*)(int)>(&std::toupper)

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