C++ cin whitespace question

和自甴很熟 提交于 2019-11-28 06:46:21

问题


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.


回答1:


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 );


来源:https://stackoverflow.com/questions/2735315/c-cin-whitespace-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!