Uys of Spades
Uys of Spades

Reputation: 171

How to manipulate a string to lower case and store in same variable

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

Upvotes: 0

Views: 1091

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27528

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.

Upvotes: 1

David G
David G

Reputation: 96810

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);
//      ^^^

Upvotes: 1

Related Questions