Capitalize the first letter, lower case the rest

user2999339 picture user2999339 · Nov 16, 2013 · Viewed 13.7k times · Source

I am asking a user to enter their name and I want to automatically format the name so that, no matter how they enter the name, it will appear as capital first letter, lower case the rest. For example, if they enter "joHN" the program will still output their name as "John."

I have the following code for their name input:

string name;
cout << "Please enter your first name: ";
cin >> name;

I am assuming I will have to use the toupper and tolower commands, but I am really unsure how to write something to adjust each character in the string.

Answer

Some programmer dude picture Some programmer dude · Nov 16, 2013

The simplest solution is probably to make the whole word lower-case first, then make the first character upper case.

C++ has some nice algorithms in the standard library. For this I suggest std::transform together with std::tolower. And there's of course std::toupper for the last part:

if (!name.empty())
{
    std::transform(std::begin(name), std::end(name), std::begin(name),
                   [](char const& c)
                   {
                      return std::tolower(c);
                   });

    name[0] = std::toupper(name[0]);
}