write a program to accept full name and display its short form in C++. For example: Enter string: Mohandas Karamchand Gandhi
Short form: M. K. Gandhi
Answers
Answered by
3
//program to print initials of a name
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[100];
char b[100];
int i;
int j=2;
printf(“Enter a name \n”);
gets(a);
b[0]=a[0];
b[1]=’.’;
for(i=0;i<strlen(a);i++);
{
if(a[i]==’ ‘)
{
b[j]=a[i+1];
j++;
b[j]=’.’;
j++;
}
}
for(i=strlen(a);a[i]!=’ ‘;i--)
j=j-2;
for(i=i+1;i<strlen(a);i++)
{
b[j]=a[i];
j++;
}
b[j]=’\0’;
printf(“The initial is : \n”);
for(i=0;i<strlen(b);i++)
{
if(b[i]==’ ‘)
i++;
else
printf(“%c”,b[i]);
}
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[100];
char b[100];
int i;
int j=2;
printf(“Enter a name \n”);
gets(a);
b[0]=a[0];
b[1]=’.’;
for(i=0;i<strlen(a);i++);
{
if(a[i]==’ ‘)
{
b[j]=a[i+1];
j++;
b[j]=’.’;
j++;
}
}
for(i=strlen(a);a[i]!=’ ‘;i--)
j=j-2;
for(i=i+1;i<strlen(a);i++)
{
b[j]=a[i];
j++;
}
b[j]=’\0’;
printf(“The initial is : \n”);
for(i=0;i<strlen(b);i++)
{
if(b[i]==’ ‘)
i++;
else
printf(“%c”,b[i]);
}
}
mg2660:
Its not the way I wanted. it shows like Entered name: Mohandas Karamchand Gandhi and Short form: M.
Answered by
1
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
std::istringstream is(line);
return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names
{
private: std::vector<std::string> full_name_;
void TakeInput()
{ std::cout << "Enter the name: " << std::endl;
std::string input;
getline(std::cin,input);
full_name_ = LineSplit<std::string>(input);
}
void DisplayInitialsOfFirstNames() const {
std::cout << "Mr. ";
for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
std::cout << full_name_[i][0] << ". ";
}
};
void DisplayLastName() const {
std::cout << full_name_.back() << std::endl;
}
public:
void work() {
TakeInput();
DisplayInitialsOfFirstNames();
DisplayLastName();
};
};
int main(){
Names n;
n.work();
}
#include <iterator>
#include <sstream>
#include <vector>
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
std::istringstream is(line);
return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names
{
private: std::vector<std::string> full_name_;
void TakeInput()
{ std::cout << "Enter the name: " << std::endl;
std::string input;
getline(std::cin,input);
full_name_ = LineSplit<std::string>(input);
}
void DisplayInitialsOfFirstNames() const {
std::cout << "Mr. ";
for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
std::cout << full_name_[i][0] << ". ";
}
};
void DisplayLastName() const {
std::cout << full_name_.back() << std::endl;
}
public:
void work() {
TakeInput();
DisplayInitialsOfFirstNames();
DisplayLastName();
};
};
int main(){
Names n;
n.work();
}
Similar questions