1

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?

3
  • 2
    How about foo.name = foo.nameFirst + " " + foo.nameLast Commented Feb 12, 2014 at 3:30
  • Using >> as you have, parsing stops when whitespace is encountered, so any names with spaces will be truncated. If you don't care, then you can recombine the words into a single name with nameFirst + ' ' + nameLast. Otherwise, you may want to use e.g. get() to read into a character array until a newline is encountered (a poor imitation of getline(), so you can handle surnames like "Von Muellerhoff". More generally, to learn what std::strings can do, see en.cppreference.com/w/cpp/string/basic_string Commented Feb 12, 2014 at 3:34
  • There's also iterators: foo.name.assign(istreambuf_iterator<char>(cin.rdbuf()), istreambuf_iterator<char>()); (as apposed to the preferred std::getline() of course). Commented Feb 12, 2014 at 3:40

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.