190k views
3 votes
Write a program that reads a person's first and last names, separated by a space. Then the program outputs last name, comma, first name. End with newline. Example output if the input is: Maya Jones Jones, Maya

1 Answer

3 votes

// Writing a C++ program for given scenario

// Making two variables to read first and last name

#include <iostream> // Including standard Input/output stream

#include<string> // Including string stream to use getline function

using namespace std;

// Main Function

int main()

{

string inputString =" "; // Variable for String input

cout<<"Enter full name :"; // Statement to get input

getline(cin,inputString); // using get line function to get input

/*

Here getline function is used to get full line input. If you will use

cin>> inputString than it will take input from stream until a space is

written, all the input after space will be discarded.

*/

// Taking length of the input

int len = inputString.length();

// Index to get index of string where space is entered by the user

int index =0;

// Variable to store first name

char firstname[len];

/*

This for loop will start a counter (i) from end of string entered and will store all the characters in the variable declared above until space is hit

*/

for(int i=0;i<len;i++){

if(inputString[i]!=' ')

firstname[i]=inputString[i];

else{

index = i;

cout<<index<<endl;

break;

}

}

// For loop to output last name

for(int i=index+1;i<len;i++){

cout<<inputString[i];

}

// output the comma

cout<<",";

// output the stored first number

cout<<firstname<<endl;

return 0;

}

User Djaouad
by
8.5k points