String Variables (Two Word Input)

Jun 21, 2010 at 9:54pm
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;
}
}
Jun 21, 2010 at 10:13pm
You don't need both of these:

1
2
cin >> fullname;  // this will only read in one word
getline(cin,fullname); // this will read in everything typed. 


You just need this one:

 
getline(cin,fullname);


No point in reading it in twice!
Last edited on Jun 21, 2010 at 10:13pm
Jun 21, 2010 at 10:43pm
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
Jun 21, 2010 at 10:53pm
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;
Last edited on Jun 21, 2010 at 10:54pm
Jun 21, 2010 at 10:57pm
Great, that works-- thank you!
Jun 22, 2010 at 7:28am
It also works if you ask for the name before the age... Probably something to do with getline().
1
2
3
4
5
6
string fullname;
int age;
cout << "What is your full name? ";
getline(cin, fullname);
cout << "What is your age?";
cin >> age;
Last edited on Jun 22, 2010 at 7:29am
Jun 22, 2010 at 10:01am
getline() removes the 'end of line' char but >> does not. I think >> will skip leading white-space, but not trailing white-space.
Jun 25, 2010 at 1:32am
use gets(your_variable);
you will need the stdio.h file for this one.
Jun 25, 2010 at 2:44am
Actually the old C function gets(char*); should be avoided at all costs. It is very unsafe.

http://en.wikipedia.org/wiki/Gets
Last edited on Jun 25, 2010 at 2:47am
Topic archived. No new replies allowed.