Dremendo Tag Line

Input a name and print the initial along with title in C++

String Methods - Question 5

In this question, we will see how to input a name and print the initial first and then the title in C++ programming. To know more about string methods click on the string methods lesson.

Q5) Write a program in C++ to input a name and print the initial first and then the title.

Example:
Input ->   MOHIT KUMAR AGARWAL
Output ->  M.K. AGARWAL

Program

#include <iostream>
#include <conio.h>
#include <string.h>
#include <stdio.h>

using namespace std;

int main()
{
    char s[50];
    int i,lsp;

    cout<<"Enter a name\n";
    gets(s);

    // Finding the last space position
    for(i=strlen(s)-1; i>=0; i--)
    {
        if(s[i]==' ')
        {
            lsp=i;
            break;
        }
    }

    cout<<"The initials of the name is\n";
    for(i=0; i<lsp; i++)
    {
        if(i==0 && s[i]!=' ')
        {
            cout<<s[i]<<".";
        }
        else if(s[i]==' ' && s[i+1]!=' ')
        {
            cout<<s[i+1]<<".";
        }
    }

    // Printing the title
    for(i=lsp; i<strlen(s); i++)
    {
        cout<<s[i];
    }
    return 0;
}

Output

Enter a name
Mohandas Karamchand Gandhi
The initials and the title is
M.K. Gandhi
video-poster