views:

112

answers:

1

Programming novice here. I'm trying to allow a user to enter their name, firstName middleName lastName on one line in the console (ex. "John Jane Doe"). I want to make the middleName optional. So if the user enters "John Doe" it only saves the first and last name strings. If the user enters "John Jane Doe" it will save all three.

I was going to use this:

cin >> firstName >> middleName >> lastName;

then I realized that if the user chooses to omit their middle name and enters "John Doe" the console will just wait for the user to enter a third string... I know I could accomplish this with one large string and breaking it up into two or three, but isn't there a simpler way to do it with three strings like above?

I feel like I'm missing something simple here...

Thanks in advance.

+3  A: 

Use getline and then parse using a stringstream.

#include <sstream>

string line;
getline( cin, line );
istringstream parse( line );

string first, middle, last;
parse >> first >> middle >> last;
if ( last.empty() ) swap( middle, last );
Potatoswatter
Since buddyfox is a newbie, I threaten to remove my up-vote because you omitted the `std::` prefix. `:)`
sbi
@sbi: lol, on `std::` we differ. I prefer not to scare newbies and not to torture myself ;v) .
Potatoswatter
@sbi: Thanks for the fix.
Xavier Ho
Thanks for the quick answer! That's similar to what I was thinking, but I posted this question because I'm still wondering about the simplicity of it all... I'm looking at a textbook with a related problem and it says "Hint: You may want to use three string variables rather than one large string variable. You may find it easier to not use getline." Any idea what they're getting at?
buddyfox
@buddyfox: nope. Far as I know `getline` is the only easy way to recognize a newline at all. I don't suppose it includes answers?
Potatoswatter
Unfortunately it doesn't. It just gives the hint to use three variables and no getline like I tried to do in my original question...
buddyfox