C++ program to convert first character uppercase in a sentence

C++ program to convert the first character of each word in a sentence to uppercase

In this program, we will write a code to convert the first character of each word in a sentence to uppercase using C++ programming language. The algorithm will read a string from the user and convert the first character of each word to uppercase and the rest of the characters to lowercase.

Here is the code for converting the first character of each word in a sentence to uppercase in C++:

#include
#include
#include

using namespace std;

int main()
{
    string str;
    cout<<"Enter a sentence: ";
    getline(cin, str);

    for(int i=0; i<str.length(); i++)
    {
        if(i == 0 || str[i-1] == ' ')
        {
            str[i] = toupper(str[i]);
        }
        else
        {
            str[i] = tolower(str[i]);
        }
    }
    cout<<"The sentence with first letter of each word capitalized: "<<str<<endl;
    return 0;
}

In the code above, we have used getline function to read a sentence from the user including spaces. The loop runs through the length of the string and checks if the current character is the first character of a word or not. If it is the first character of a word, we convert it to uppercase using toupper function. If it's not the first character, we convert it to lowercase using tolower function. Finally, the code prints the sentence with first letter of each word capitalized.

This code will produce the desired output and will be helpful in converting the first character of each word in a sentence to uppercase.

Submit Your Programming Assignment Details