I'm trying to make a program where it displays the users name based on what they entered. For example if the user enters: John Average User the output would display User, John A. And if the user enters John A. User the program would output User, John A. The problem I'm running into is if no middle name is entered. If I enter John User the program will not execute until I enter a third name. I want my program to be able to output if no middle name is entered.

#include<iomanip>
#include<iostream>
#include<string>

using namespace std;

string firstName;
string lastName;
string middleName;
string middleInitial;

string placePeriod();


int main(){
	cout<<"Enter your first, middle and last name: "; cin>>firstName >>middleName >>lastName;
	if(lastName==""){
		lastName=middleName;
		middleName="";
	}

	cout<<lastName <<", " <<firstName<<" " <<middleName[0] <<placePeriod() <<endl;
}

string placePeriod(){
	if(middleName!=""){
		return ".";
	}
	else{
		return "";
	}
}

Recommended Answers

All 3 Replies

How about having the user enter their whole name in one string, and then you take that string apart for the words in it. If there are two words, there is no middle name.

Read the line using getline() . Find the last SPACE. Everything before is the first/middle name, after is last name.

the problem is because you are reading in 3 variables, so if you do not enter data to the command line properly the program does not work:

cout<<"Enter your first, middle and last name: "; cin>>firstName >>middleName >>lastName;

as suggested above try either using getline, or just having the name read in as one string. if you do the latter you can substring and then continue out to your if statements.

good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.