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.


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;

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

string placePeriod(){
		return ".";
		return "";
6 Years
Discussion Span
Last Post by atticusr5

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!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.