Search code examples
c++lowercasecapitalizetolowertoupper

Capitalize the first letter, lower case the rest


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.


Solution

  • The Standard Library provides the C functions std::toupper() and std::tolower() which return the upper/lower case of the specified ASCII character. So your problem could be solved with a simple for loop:

    if( !name.empty() )
    {
        name[0] = std::toupper( name[0] );
    
        for( std::size_t i = 1 ; i < name.length() ; ++i )
            name[i] = std::tolower( name[i] );
    }