To change the case of all the letters in a string object, use the std::transform() algorithm. This algorithm is defined in the standard header
#include #include #include #include // for toupper()int main(){ std::string s("hello"); // lowercase // transform the string to uppercase std::transform(s.begin(), // original string's beginning s.end(), // original string's end s.begin(), // where to write the new string? toupper); // unary operator std::cout << s; // display "HELLO"}
Alas, the program above will not compile because the name 'toupper' is ambiguous: there are two functions with this name:
1) int std::toupper(int); // from 2) template charT std::toupper(charT, const locale&); // from
We want the first function to be called. To resolve the ambiguity, we add an explicit cast:
std::transform(s.begin(), s.end(), s2.begin(), static_cast < int(*)(int) > (toupper));
This tells the compiler which version of toupper() to choose, namely the one declared in