1

I am having trouble turning strings to uppercase for an alphabetical sort. My program actually begins to slow down and freeze after the third set of words. What am I doing wrong?

string iName = list[i]->GetLastName(); // This just returns a string of a name
string jName = list[j]->GetLastName();

for(unsigned int k = 0; k < iName.length(); k++)
  {
    iName[k] = toupper(iName[k]);
  }

for(unsigned int l = 0; l < jName.length(); l++)
  {
    iName[l] = toupper(jName[l]);
  }
jordaninternets
  • 233
  • 2
  • 6
  • 15

3 Answers3

12

Use STL algorithm library:

std::for_each(iName.begin(), iName.end(), std::toupper);

or (suggested by @Kerrek SB)

std::transform(s.begin(), s.end(), s.begin(), std::toupper);
Community
  • 1
  • 1
Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • 5
    [transform](http://stackoverflow.com/questions/1489313/c-stdtransform-and-toupper-why-does-this-fail) is even better. – Kerrek SB Nov 28 '11 at 21:57
  • Ya but my version works in-place, so IMO is better for this cause. And if you wanna even shorten this code you can write `std::for_each(iName.begin(), iName.end(), [](char&c){c=std::toupper(c);});` – Hauleth Nov 28 '11 at 21:59
  • 3
    Actually, why can't you `transform` into the range itself? `std::transform(s.begin(), s.end(), s.begin(), std::toupper);`? – Kerrek SB Nov 28 '11 at 22:02
  • I don't know. I incorrectly read question in your link. My bad. Difference in our versions are that my modify in-place and your rewrite all string, what in nowadays compilers and CPUs is IMO any difference. – Hauleth Nov 28 '11 at 22:06
7

as others said, you mixed iname and jname.... and why did you do this?

Because you copy pasted!

So, a good early lesson in programming is to try and avoid copy paste! instead try and create functions.....

in your case...

void stringToUpper(string &s)
{
   for(unsigned int l = 0; l < s.length(); l++)
  {
    s[l] = toupper(s[l]);
  }
}

then you can do

stringToUpper(iName);
stringToUpper(jName);

This approach redues a LOT of errors related to copy pasting and in general, helps make your programs a lot more modular

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • 2
    Now he is going to copy and paste your function. :) You are right though, this is a good habit to get into. – duckbrain Sep 19 '13 at 04:24
-2

The standard suggests that you should not use [] operator on string to modify it's contents. string is designed as an immutable object and your code is breaking that standard. So I guess the answer is that it's hard to say what may be happening because you are using the class in a way in which it was not designed. It could be messing up some internal index or something else. We don't know what the string class may be doing internally.

That said, it seems like it should work :)

pedorro
  • 3,079
  • 1
  • 24
  • 24