【问题标题】:Combining Two Strings into One Variable in C++在 C++ 中将两个字符串组合成一个变量
【发布时间】: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怎么样
  • 像你一样使用&gt;&gt;,遇到空格时解析停止,因此任何带有空格的名称都将被截断。如果你不关心,那么你可以用nameFirst + ' ' + nameLast 将这些词重新组合成一个名字。否则,您可能想使用例如get() 读入字符数组直到遇到换行符(对 getline() 的拙劣模仿,因此您可以处理像“Von Muellerhoff”这样的姓氏。更一般地,要了解 std::strings 可以做什么,请参阅 @987654321 @
  • 还有迭代器:foo.name.assign(istreambuf_iterator&lt;char&gt;(cin.rdbuf()), istreambuf_iterator&lt;char&gt;());(当然与首选的std::getline()相对)。

标签: c++


【解决方案1】:

你可以使用

cin >> foo.nameFirst >> foo.nameLast;

cin &gt;&gt; 将在空格处解析停止,因此您可以在一行中输入全名,如James Bond

将两个字符串合二为一:

string fullName = foo.nameFirst + " " + foo.nameLast;

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多