Hi I am having trouble with this program, because if the user inputs a multiple word answer for the second question, it will only display the first word of the given answer. And I tried using getline(cin, answer) instead, but that just did not even ask me for an answer then. I am having a lot of trouble with this should be simple problem, any help would be great!


Write a program which asks the user to enter his/her age, followed by another question. If the user enters 18 or less for age, ask what kind of school they are in. If the person enters an age between 19 and 24 (inclusive), ask if the student is in college. If the person enters an age which is 25 or older, ask what the person does for a living. You must include at least one "else" statement (properly used) in this program.

#include <iostream>
#include <string>

using namespace std;

int main()
{
	int age;
	string answer;

	cout << "Please enter your age: ";
	cin >> age;

	if (age <= 18)
	{
		cout << "Are you in elementary, middle school, or high school? " << endl;
	}

	else if ((age >= 19) && (age <= 24))
	{
		cout << "Are you in college? ";
	}

	else 
	{
		cout << "What do you do for a living? ";
	}

	cin >> answer;

	cout << "You answered '" << answer << "'." << endl;


}

You might have a dangling newline on the cin, so when you try getline it returns an empty line before you even have time to enter anything. Simple solution, replace the "cin >> answer;" part with:

cin.ignore(); //this will ignore any newlines that are on the input buffer but not yet red.
getline(cin,answer); //then read the line.
Comments
Good Answer :)

Agreed, you have a dangling newline because of the numeric input. Add an ignore statement to extract it.

thanks a lot, I'm new to c++ so I didn't even know what an ignore statement was and didn't see that in my text book. Thanks!

This article has been dead for over six months. Start a new discussion instead.