In: Computer Science
Using string functions and all other programming features discussed in the class, write a program that will prompt a user to input their name (first and last). Ex: Please enter your first and last name: John Doe Then, output the string. Next, prompt the user to input their nickname. Ex: Enter your nickname: Rowdy Then modify the name string to consist of the person’s last name comma, nickname (backwards, in all caps, enclosed in double quotes) and first name. Then output the modified string. Ex: Doe, “YDWOR” John Bonus (+10) Output first and last name alternating every two characters: John Doe Ex: JoDohne Tim Wheaterton Ex: TiWhmeaterton NOTE: This program should loop, prompting the user to decide whether or not he or she wishes to enter another name. Ex: Do you wish to enter another name(y/n)?
comment program must have getline and concatenation also in c++
Code:
name.cpp:
#include<iostream>
#include<string> //to use
getline()
#include<algorithm> //to use
reverse()
using namespace std;
int main()
{
string c="y";
//initialize choice to continue to yes
do
{
string name;
cout<<"Please enter your
first and last name: ";
getline(cin,name);
//take input with space
string
first="",last=""; //initialize first and last name to
null strings
int flg=0;
//flag to indicate end of first name
for(int
i=0;i<name.length();i++) //seperation of first and
last name
{
if(name[i]=='
') //when space detected change flag
{
flg=1;
continue;
}
if(flg==0) //when flag==0 (no space
detected yet) copy characters to first name
{
first=first+name[i];
}
else
////when flag==1 (space
detected) copy characters to last name
{
last=last+name[i];
}
}
string nname; //nickname
cout<<"Enter your nickname:
";
getline(cin,nname);
//take nickname
reverse(nname.begin(),
nname.end()); //reverse nickname
for(int
i=0;i<nname.length();i++) //change case of nickname
to UPPER
{
if
(nname[i]>='a' && nname[i]<='z')
nname[i] = nname[i] - 32;
}
name=last+", \""+nname+"\"
"+first; //modify string name as
required
cout<<"Modified String :
"<<name<<endl;
string alter=""; //to
store alternating characters
int
f=first.length(),i=0; //initialize counter for first
anme and its end
int
l=last.length(),j=0; //initialize counter for last name
and its end
while(i<f||j<l)
//as first name can be small than last name or
vice versa hence used || (OR)
{
if(i<f) //to make sure don't copy
NULL character '\0'
{
alter=alter+first[i];
i++;
if(i<f) //to make sure don't copy
NULL character '\0'
{
alter=alter+first[i];
i++;
}
}
if(j<l) //to make sure don't copy
NULL character '\0'
{
alter=alter+last[j];
j++;
if(j<l) //to
make sure don't copy NULL character '\0'
{
alter=alter+last[j];
j++;
}
}
}
cout<<"Alternating every two
character string: "<<alter<<endl; //Output
alternating string
cout<<"Do you wish to enter
another name(y/n)? "; //Ask if you want to
continue
cin>>c;
cin.ignore(); //used to
ignore enter key hitted for next getline()
}while(c=="y");
return 0;
}
Screenshot:
Output: