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,130
  • 11
  • 47
  • 72

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
  • 464,258
  • 100
  • 912
  • 987
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,353
  • 1
  • 21
  • 38