0

I have a piece of code that asks for user input, it is type "string" and its a really simple process, i want whatever the user inputs to be converted using the tolower() function. It does exactly as its supposed to do, but i can't seem to assign it to the same variable. Any help please?

#include <locale>
#include <string>
#include <iostream>
//maybe some other headers, but headers aren't the problem, so I am not going to list them all

while (nCommand == 0)
        {  
            locale loc;
            string sCommand;
            cin >> sCommand;

            for (int i = 0; i < sCommand.length(); ++i)
            {
            sCommand = tolower(sCommand[i],loc);
            cout << sCommand;
            }

For example if the user types in Help sCommand would be h

How I want it to look like it that if the user types in HELP or Help or HeLp

sCommand should be 'help' either way

Uys of Spades
  • 173
  • 1
  • 9
  • This was closed as duplicate but the referred selection "solution", at http://stackoverflow.com/questions/313970/stl-string-to-lower-case, is UB code (in general), so I voted to reopen. Please before closing as dup make sure that the referred to answer works. It's difficult to make an OP of some other question change his or her selection of "solution". – Cheers and hth. - Alf May 29 '14 at 17:36
  • @Cheersandhth.-Alf I noted the UB and notified the poster, and I intended to re-open this but forgot. I am tempted to add a correct answer to that post, but it would get lost amongst all the highly voted answer. It is annoying when buggy answers get so many up-votes. – juanchopanza May 29 '14 at 18:02
  • @Cheersandhth.-Alf: *sigh* No it's not. What total nonsense. You wanna quit stomping around, baselessly accusing everybody else of being wrong? (`[C++11: 21.4.1.1.2/10]`/`[C99: 7.4.2.1/3]`) – Lightness Races in Orbit May 29 '14 at 23:12

2 Answers2

1

You're assigning a string to a character when really what you want to do is assign the character stored at the position to the lower case version.

Therefore change this:

sCommand = tolower(sCommand[i], loc);

to this:

sCommand[i] = tolower(sCommand[i], loc);
//      ^^^
David G
  • 94,763
  • 41
  • 167
  • 253
1

This is another case where Boost String Algorithms would reduce the whole problem to one single expression:

boost::algorithm::to_lower(sCommand)

Try the Boost libraries. It will help you immensely in the long run and let you concentrate on real problems rather than silliness like being the one-millionth programmer to write their own "convert string to lower-case" function.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62