[英]How output a full name that starts with last name? What if the the first name or last name consist of words?
我需要一些帮助(C++)
制作一个程序,输入一次全名,但输出全名将以姓氏开头。
我附上了我的代码,但此代码只会读取名字的第一个单词或姓氏的第一个单词。 如果名字或姓氏有两个词怎么办? 谢谢你。
<pre>
#include <iostream>
#include <string>
using namespace std;
main()
{
string first, middle, last;
cout << "What is your full name? ";
cout << endl << "---> ";
cin >> first >> middle >> last;
cout << "---> " << last << ", " << first << " " << middle;
cout << endl;
return 0;
}
<code>
如果读取失败(即未读取任何字),则输入流将处于失败状态。 因此,解决方案是在每次读取后测试流状态。
if (cin >> first)
{
if (cin >> middle)
{
if (cin >> last)
{
//...
}
else
{
last = middle;
}
}
}
只有当它不为空时,您才应该测试每个名称和输出。
我认为这可能就是您的意思,从示例名称来看:
“第一个中间middle2 ...中间n最后”
你想输出
“最后,第一个中间......中间-n”。
为此,您可以..
std::getline(cin, name)
获取名称。 使用cin >> name
会在遇到空格" "
时截断字符串。 这意味着只在空格之前获取第一个“单词”。
为避免这种情况,请使用getline
。
使用string::find_last_of(" ")
使用string::substr(pos, span)
获取所需的子字符串。
http://www.cplusplus.com/reference/string/string/substr/
这是代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name, last;
cout << "What is your full name? ";
cout << endl << "---> ";
getline(cin,name);
int idx;
idx = name.find_last_of(" ");
cout << idx << endl;
last = name.substr(idx+1);
cout << "---> " << last << ", " << name.substr(0, idx);
cout << endl; return 0; }
示例输出:
What is your full name :
---> first middle middle2 middle3 last
28
---> last, first middle middle2 middle3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.