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?
foo.name = foo.nameFirst + " " + foo.nameLast>>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 withnameFirst + ' ' + nameLast. Otherwise, you may want to use e.g.get()to read into a character array until a newline is encountered (a poor imitation ofgetline(), so you can handle surnames like "Von Muellerhoff". More generally, to learn whatstd::strings can do, see en.cppreference.com/w/cpp/string/basic_stringfoo.name.assign(istreambuf_iterator<char>(cin.rdbuf()), istreambuf_iterator<char>());(as apposed to the preferredstd::getline()of course).