Printing sentence case using string in C++


This is a C++ program that takes a sentence as input and converts it to sentence case (i.e., capitalizes the first letter of the first word and converts all other letters to lowercase). The program works as follows:

  • The input sentence a is defined and initialized using the getline function to read a line of text from the console.
  • The first character of the sentence is checked to see if it is a lowercase letter (ASCII code between 97 and 122). If it is, its ASCII code is subtracted by 32 to convert it to uppercase.
  • A loop is used to iterate over the remaining characters of the sentence. For each character, if it is an uppercase letter (ASCII code between 65 and 90), its ASCII code is added by 32 to convert it to lowercase.
  • Another loop is used to check for periods followed by spaces, indicating the end of a sentence. For each such occurrence, if the next character (i.e., the first character of the next word) is a lowercase letter, its ASCII code is subtracted by 32 to capitalize it.
  • The resulting value of the sentence is printed to the console using the cout object.
  • The program exits with a return value of 0.

Overall, this program demonstrates how to convert a sentence to sentence case in C++ by manipulating the ASCII codes of the characters in the string.

Source Code

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int i;
    string a;
    cout<<"\nEnter the Sentence:";
    getline(cin,a);
    cout<<"\nSentenced case:";
    if(a[0]>=97&&a[0]<=122)
    {
        a[0]-=32;
    }
    for(i=1;a[i]!='\0';i++)
    {
        if(a[i]>=65 &&a[i]<=90)
        {
            a[i]+=32;
        }
    }
    for(i=1;a[i]!='\0';i++)
    {
        if(a[i]==46 && a[i+1]==32)
        {
            if(a[i+2]>=97&&a[i+2]<=122)
            {
                a[i+2]-=32;
            }
        }
    }
    cout<<a;
    return 0;
}
To download raw file Click Here

Output

Enter the Sentence:tutor joe's computer education
Sentenced case:Tutor joe's computer education

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples