but I can't do that because if a user want to type in just the first and last name then the program will still be waiting for one more string. Should I use getline and find out how many names the user entered by counting the number of spaces or something and then extract the names using substrings?
Should I use getline and find out how many names the user entered by counting the number of spaces or something and then extract the names using substrings?
That's one option. Though you might want to write your own loops to deal with excess whitespaces, in case there are any..
Another option is to getline and feed it to a stringstream. Then use >> three times. If there are only two strings in the line, fail() method will return true.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
usingnamespace std;
char control = 'y';//this variable is used by user to stay in or exit out of do-while loop
do
{
cout << "Enter full name: ";
string first, middle, last;
char next;
cin >> first >> middle;
cin.get(next);
if(next == '\n')
{
last = middle;
cout << last << ", " << first << endl;
}
else
{
cin >> last;
cout << last << ", " << first << " " << middle.substr(0, 1) << ".";
}
cout << "\n\nWould you like to run the program again? (Y/N): ";
cin >> control;
while ((control != 'y') && (control != 'n'))
{
cout << "Incorrect input. Would you like to run the program again? (Y/N): ";
cin >> control;
control = tolower(control);
}
cin.ignore();
cin.clear();
}while(control == 'y');
cout << "Press key to exit: ";
char exit;
cin >> exit;
return 0;
}