Can getline (cin) store more than one variable?

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

using namespace std;

int main()
{
    //Variables
    string first_name;
    string last_name;

    cout << "Please enter your first and last name: ";

    getline (cin, first_name, last_name);

    cout << "Hello, " << first_name << last_name << ".";
}


This fails at the getline, only working successfully if only one variable is used. I'm very new to C++ and learning with several books. One suggests it'll work using cin >> variable1 >> variable2 but I was hoping to avoid using cin >>. So, can getline store more than one variable on a single prompt? If so what's the format?
What do you expect to happen? Why do you want to avoid using the formatted extraction operator?
getline gets the whole line,
you want to use cin to get one word at a time

try
1
2
3
cin >> first_name;
cin >> last_name;
cout << " Name is: " << first_name << " " << last_name << endl;
@Pindrought: why not cin >> first_name >> last_name;?

Also:
http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
Don't use first-name-last-name system.
Last edited on
Thanks guys, I'll use cin >> instead of getline. I had a misconception that getline was more efficient to use, clearly not in all cases or needs. :)
Last edited on
@LB my reasoning that I posted it that way is only because it's a lot less confusing on the eyes for newer programmers to see if that way versus all on one line.

Mary Magdalene, getline is better in a sense that if you're dealing with names that may have more than one word you'll be sure to get all of the info. Some people's names have multiple spaces in them
You should never worry about efficiency. Always use the most elegant practical solution, and worry about optimization only after you have profiled your working code and found the bottlenecks.
Topic archived. No new replies allowed.