How would I write this program?

The program is supposed to take a first, middle, and last name and put it in the following format:

<last name>, <first name> <middle initial>.

The thing I'm having trouble with is that a user is supposed to be able to also take a first and last name and put it in the format:

<last name>, <first name>

If the program were to have to do just the first part then I think it would be pretty easy. I would just use

1
2
3
string first, middle, last;
cin >> first >> middle >> last;
....


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.
Thanks hamsterman. I ended up using a different method than what you suggested but your post helped me regardless.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <string>
#include <cctype>



int main()
{
	using namespace 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;
}
Topic archived. No new replies allowed.