0
string str("fujian");
string newstr;
transform(str.begin(), str.end(), newstr.begin(), ::toupper);
cout << newstr << endl;

why the result is nothing for this code sample about string toupper?

jiafu
  • 6,338
  • 12
  • 49
  • 73

2 Answers2

3

Your code writes past the end of newstr and therefore has undefined behaviour.

Try either of the following instead:

// version 1
string str("fujian");
string newstr(str);
transform(newstr.begin(), newstr.end(), newstr.begin(), ::toupper);
cout << newstr << endl;

// version 2
string str("fujian");
string newstr;
transform(str.begin(), str.end(), std::back_inserter(newstr), ::toupper);
cout << newstr << endl;
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You haven't got any space allocated for newstr.

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

Community
  • 1
  • 1
Cristina_eGold
  • 1,463
  • 2
  • 22
  • 41