Hello,
I am working on a program where I have to get a full name from the person putting in input. I have to do this through one string, not by splitting the name into first and last name variables. This is the code I have so far but it's only printing the last name entered, not both first and last. What am I doing wrong?
Thanks for your help!
Sarah
#include <iostream>
#include <string>
//Write a program which asks for the user's name and age and then display the appropriate response.
using namespace std;
int main ()
{
int age;
cout << "What is your age?";
cin >> age;
string fullname;
cout << "What is your full name? ";
cin >> fullname;
getline(cin,fullname);
cout << "Okay, " << fullname << "," << endl;
if (age >= 18)
{
cout << "You can smoke cigarettes." << endl;
cout << "You can vote." << endl;
}
if ((age >= 18) && (age <= 30))
{
cout << "You can join the military." << endl;
}
if (age >= 21)
{
cout << "You can drink alcohol." << endl;
}
if (age >= 62)
{
cout << "You can draw Social Security." << endl;
}
}
Thanks for your feedback. I tried just using
getline(cin,fullname);
but then I wasn't able to enter a name. After I entered an age, the rest of the program was simply displayed. Do you have any other tips?
Thanks again!
Sarah
Okay, after inputting the age there is a end of line character left in the buffer from when you hit return. You need to absorb that. You can use the std::ws manipulator like this:
1 2 3 4 5 6 7 8 9 10
int main()
{
int age;
cout << "What is your age?";
cin >> age;
string fullname;
cout << "What is your full name? ";
cin >> ws; // consume any white-space characters
getline(cin, fullname);
cout << "Okay, " << fullname << "," << endl;