Pregunta

EDIT:I see how it works now, in the string myString it takes everything after the space. So how would this be done if you wanted to take the first name and not the last name, since now you can't use the space if you do that.

I'd like to get the user to input their first and last name, then I'd like to print their last name only to the screen.

I know how to ask the user the question, and I was using getline to get the string of their name. But once that's happened how do I take their last name and print it out without printing out their first name as well. I can't seem to, I guess, isolate each part of the string.

I tried searching for an answer to this, but I can't seem to find one.

using namespace std;
int main()
{
    string firstName;
    string lastName;

    cout << "Welcome to my store!" << endl;
    cout << "---------------------------" << endl;
    cout << "Please enter your first and last name. ";
    getline(cin, firstName);
    cout << "\nThank you " << firstName << " for shopping with us!";
}

I left the getline as is because I tried getline(cin, firstName, lastName) in an attempt to assign each word input by the user to a string but that didn't work.

¿Fue útil?

Solución

I think this is what you are looking for(for printing the last name alone)

#include <iostream>
#include <string>
using namespace std;
int main()
{
string myString;
int i;
cout<<"\n Enter a name:";
getline(cin, myString, '\n');//Get a name where first name and last name is seperated by a space
i=myString.find(' ');//find the find occurance of space in that string 
cout<<"thanks for shopping:";
cout<<myString.substr(i,myString.length());//printing the rest of the string from the occurence of space
return 0;
} 

When you give input like 'Sachin Tendulkar' It says 'thanks for shopping:Tendulkar'

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top