C++ std::transform() and toupper() ..why does this fail?

sivabudh picture sivabudh · Sep 28, 2009 · Viewed 28.1k times · Source

I have 2 std::string. I just want to, given the input string:

  1. capitalize every letter
  2. assign the capitalized letter to the output string.

How come this works:

  std::string s="hello";
  std::string out;
  std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);

but this doesn't (results in a program crash)?

  std::string s="hello";
  std::string out;
  std::transform(s.begin(), s.end(), out.begin(), std::toupper);

because this works (at least on the same string:

  std::string s="hello";
  std::string out;
  std::transform(s.begin(), s.end(), s.begin(), std::toupper);

Answer

hrnt picture hrnt · Sep 28, 2009

There is no space in out. C++ algorithms do not grow their target containers automatically. You must either make the space yourself, or use a inserter adaptor.

To make space in out, do this:

out.resize(s.length());

[edit] Another option is to create the output string with correct size with this constructor.

std::string out(s.length(), 'X');