198k views
4 votes
A String variable, fullName, contains a name in one of two formats:last name, first name (comma followed by a blank), orfirst name last name (single blank)Extract the first name into the String variable firstName and the last name into the String variable lastName. Assume the variables have been declared and fullName already initialized. You may also declare any other necessary variables.

User Zyberzero
by
6.4k points

1 Answer

3 votes

Answer:

#include <iostream>

using namespace std;

int main()

{

char fullname[30];

string fname="",lname="";

int i,j;

cout<<"Enter fullname\\";

cin.getline(fullname,30); //so that blank can be read

for(i=0;fullname[i]!=' ';i++)

fname+=fullname[i]; //fistname will be saved

cout<<"\\";

for(j=i;fullname[j]!='\0';j++)

lname+=fullname[j]; //lastname will be saved

cout<<"\\Firstname : "<<fname<<"\\Lastname : "<<lname;

return 0;

}

OUTPUT :

Enter fullname

John thomson

Firstname : John

Lastname : thomson

Step-by-step explanation:

cin.getline() should be used instead of cin in case of strings so that space can be read otherwise after blank string will be ignored.

User Demwis
by
5.8k points