Eitan Myron
Eitan Myron

Reputation: 159

Combining Two Strings into One Variable in C++

I am en process of writing a simple program that assigns given student names into groups of whatever interval requested. Currently, I am focusing on the function that reads the name of the students. Here is the code:

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

Since I cannot use getline(), I am forced to create two strings, one for each section of the student's full name. How can I rewrite this code to allow for it to take the full name without creating two variables and without using getline()? Or, if such isn't possible, how can I use a method within the class to combine the two strings into one?

Upvotes: 1

Views: 10921

Answers (1)

herohuyongtao
herohuyongtao

Reputation: 50657

You can just use

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

cin >> will parse stops at white spaces, so you can just input the full name in one line split by space like James Bond.

To combine two strings into one:

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

Upvotes: 3

Related Questions