0

I'd like to ask the user for their first and last name by using a string variable, then use the first name they entered in that string and print it out.

string name;

cout << "What is your first and last name? ";
cin >> name;
cout << "Thank you " << name  << " for shopping with us!";

Where the name variable is in the second cout statement I'd like to just use their first name, with the current setup i have, it outputs both their first and last names.

Christoph
  • 221
  • 1
  • 4
  • 11
  • http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c – Robert Harvey Feb 13 '14 at 18:47
  • 2
    How do you identify a firstname and a lastname? - Some people will enter their middle name, too, in some countries (i.e.Spain) people have two last names separated by a space. Maybe you should ask the user to enter them separate. – johannes Feb 13 '14 at 18:49
  • How does that code not do exactly what you asked? The extractor delimits input on a whitespace character. Therefore you should only see the first name they entered. – David G Feb 13 '14 at 18:54

4 Answers4

2

You can use getline to only take up to the first space, put the first name in one variable, then read to the end of the line for the last name in a different variable. If you need the two concatenated, then do so afterward. Example:

string first, last, name;

getline(cin, first, ' ');
getline(cin, last);
cout << "Thank you " << first << " for shopping with us!";
name = first + ' ' + last; //Assuming you want a space in between
IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
0

You'll need to split your string based on white space - check out this QA: Split a string in C++?

Community
  • 1
  • 1
genesys
  • 310
  • 1
  • 4
  • 11
0

There are many ways to do it, some of which are easier than others. For a possible duplicate post check here: Split a string in C++? (many people probably refrenced this).

You can also change it so that it says:

string fname;
string lname;

cout << "What is your first name? ";
cin >> fname;
cout << "What is your last name? ";
cin >> lname;
cout << "Thank you " << fname  << " for shopping with us!";

This solution is the easiest, but you will earn more if you follow the link above.

Community
  • 1
  • 1
Minkus CNB
  • 67
  • 7
0

If you want to have a single input and split it for output, you can do something like this:

std::string line, fname, lname;
std::getline(std::cin, line);
std::istringstream iss(line);
iss >> fname >> lname;
std::cout << "Thank you, " << fname << ", for shopping with us!" << std::endl;
Zac Howland
  • 15,777
  • 1
  • 26
  • 42