【发布时间】:2014-02-12 03:27:08
【问题描述】:
我正在编写一个简单的程序,将给定的学生姓名分配到所要求的任何间隔组中。目前,我专注于读取学生姓名的功能。 代码如下:
class student
{
public:
string nameFirst;
string nameLast;
};
student typeName()
{
student foo;
cout << "Type in a student's first name: ";
cin >> foo.nameFirst;
cout << "Type in that student's last name: ";
cin >> foo.nameLast;
cout << "\n";
return foo;
}
由于我不能使用getline(),我不得不创建两个字符串,一个用于学生全名的每个部分。如何重写此代码以允许它在不创建两个变量且不使用getline() 的情况下采用全名?或者,如果不可能,我如何使用类中的方法将两个字符串合并为一个?
【问题讨论】:
-
foo.name = foo.nameFirst + " " + foo.nameLast怎么样 -
像你一样使用
>>,遇到空格时解析停止,因此任何带有空格的名称都将被截断。如果你不关心,那么你可以用nameFirst + ' ' + nameLast将这些词重新组合成一个名字。否则,您可能想使用例如get()读入字符数组直到遇到换行符(对getline()的拙劣模仿,因此您可以处理像“Von Muellerhoff”这样的姓氏。更一般地,要了解std::strings 可以做什么,请参阅 @987654321 @ -
还有迭代器:
foo.name.assign(istreambuf_iterator<char>(cin.rdbuf()), istreambuf_iterator<char>());(当然与首选的std::getline()相对)。
标签: c++