Key Concept: Accessing Characters from Strings,C++ String Class methods, C++ Str
ID: 3608958 • Letter: K
Question
Key Concept: Accessing Characters from Strings,C++ String Class methods, C++ String Class concatenation
Write a program that uses the C++ string class to convert namesfrom the format "Last, First M." to "First M.Last" and which also displays the user's initials. Read in thefull name as a single string object (not in parts as in Lab 1).When extracting initials, use the [] operator.
(There shouldn't be a comma in the converted name.)
Remember to follow the IPO model.
When you concatenate strings, you must be adding onto an objectthat is a string. Thus, to build the string of initials, which aresingle characters, you must concatenate those single characterswith an existing string. Since string objects, by default, are theempty string, you can concatenate with it. Consider the followingexample:
Explanation / Answer
#include<iostream.h>
using namespace std;
int main()
{string name,last,first,middle,initials;
int pos,pos2;
string::size_type len;
cout<<"Enter your name in 'Last, First M.' format: ";
getline(cin,name);
pos=name.find(',',0);
last=name.substr(0,pos);
pos+=2;
pos2=name.find(' ',pos);
first=name.substr(pos,pos2-pos);
pos2++;
pos=name.find('.',pos2)+1;
middle=name.substr(pos2,pos-pos2);
initials=initials+first[0]+middle[0]+last[0];
cout<<"You're name is: "<<first<<""<<middle<<" "<<last<<endl;
cout<<"You're initials are:"<<initials<<endl;
system("pause");
return 0;
}
/* sample run
Enter your name in 'Last, First M.' format:
Jones, John P.
You're name is: John P. Jones
You're initials are: JPJ
Press any key to continue . . .
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.