5

I want to convert a std::string to uppercase. I am aware of the function toupper(), however in the past I have had issues with this function and it is hardly ideal anyway as use with a string would require iterating over each character.

Is there an alternative which works in correct manner of the time?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Manish Kumar
  • 997
  • 2
  • 13
  • 30
  • 1
    How could converting a sequence of characters to uppercase possibly not involve iterating over those characters? –  Feb 09 '18 at 17:54
  • And why would the functionality NOT ALREADY BE THERE instead of having to recreate the wheel all the time. ISNUMERIC and REPLACE being two other recent examples I've run into. – David Dec 12 '18 at 20:18

1 Answers1

2

std::toupper has several overloads

  • template <class charT> charT toupper(charT, const locale&)
  • int toupper(int ch)

So taking its address might be complicated.

You might use lambda to let compiler found the right overload:

(In addition, as char might be signed or not, and toupper expects unsigned char value (or EOF))

std::transform(s.begin(), s.end(), s.begin(),
               [](unsigned char c){ return std::toupper(c); });
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • _"as use with a string would require iterating over each character."_ Same same here, with cream, candy and syrup. –  Feb 09 '18 at 17:56