It doesn't enter any sort of loop, instead the command prompt is till waiting. You have three cin statements, and the program waits until three strings are entered. The only way around this (to my knowledge) is to ask the user ahead of time if they have a middle name. If they answer no, only use two cin statements. Otherwise, use three.
The assignment specifies that the name must be entered on one line, and if the user inputs Bob Smith, the out put must be Smith, Bob. Is it possible to use if and else statements for if there are two strings, or three strings?
and then use getline to get the input from the user
std::getline(cin, fullname)
and then use istringstream to split the name by space. You don't know if the user entered one name, two names or three names. You need to check for that. If they make a mistake, you need to ask the user to re-enter the name again.
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
#define FIRST_NAME 0
#define MIDDLE_NAME 1
#define LAST_NAME 2
int main()
{
string name[3];
unsignedint index = 0;
while (index < 3)
{
cout << "Please enter your full name (First, Middle, Last): ";
string fullname;
getline(cin, fullname);
istringstream iss(fullname);
for (index = 0; index < 3 && iss.good(); iss >> name[index], ++index);
}
cout << "First name: " << name[FIRST_NAME] << endl
<< "Middle name: " << name[MIDDLE_NAME] << endl
<< "Last name: " << name[LAST_NAME] << endl;
return 0;
}
Basically, the for loop will parse the string into three sub strings. If the string does not have three sub strings (meaning no two white spaces) the for loop ends and the index is not equal to three. It will keep asking the full name until index is equal to 3.
Ok. Thank you. Unfortunately I found out I am not allowed to use istringstream. At tutor I talked to suggested that using multiple "cin" statements I might be able to get it to read in the parts you want into the variables in my program.
Here's a revised version of my code. Not sure how to employ multiple cin statements in this way though.
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
char mInitial;
string firstName, midName, lastName, fullName;
cout << "Enter your name in the following format - First Middle Last:" << endl;
// get all chars until a whitespace delimiter is found
getline(cin, firstName, ' ');
// same as above
getline(cin, midName, ' ');
mInitial = midName[0];
// gets all chars until a newline
getline(cin, lastName);
cout << "Your name is " << lastName << ", " << firstName;
cout << " " << mInitial;
if ( midName.empty() )
cout << "" << endl;
else
cout <<"." << endl;
return 0;
}
Enter your name in the following format - First Middle Last:
MATTHEW NOAH KING
Your name is KING, MATTHEW N.
New-MacBook-Pro:~ MNK$ MATTHEW KING
-bash: MATTHEW: command not found
New-MacBook-Pro:~ MNK$