C ++ cin空格问题 [英] C++ cin whitespace question

查看:177
本文介绍了C ++ cin空格问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里编程新手。我试图允许用户输入他们的名字,firstName middleName lastName在控制台中的一行(例如John Jane Doe)。我想让middleName可选。因此,如果用户输入John Doe,它只保存名字和姓氏字符串。如果用户输入John Jane Doe,它将保存所有三个。

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.

我将使用这个:

cin >> firstName >> middleName >> lastName;

然后我意识到,如果用户选择忽略他们的中间名并输入John Doe将只等待用户输入第三个字符串...我知道我可以完成这一个一个大的字符串,并将它分成两三个,但是没有一个更简单的方法来做三个字符串像上面?

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...

>

推荐答案

使用 getline 然后使用 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 );

这篇关于C ++ cin空格问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆