bool showMenu(romanType roman){
cout << endl;
cout << "Just enter a number to choose an option" << endl;
cout << "1: Print the Roman Numeral" << endl;
cout << "2: Print the decimal value" << endl;
cout << "3: Enter a new Roman Numeral" << endl;
cout << "4: Quit the program" << endl;
cout << endl;
while (true) {
cout << "Your choice:" << endl;
int input;
cin >> input;
if (input == 1) {
cout << roman.getRomanString() << endl;
} else if(input ==2) {
cout << roman.getDecimalValue() << endl;
} else if(input == 3) {
return true;
} else if(input == 4) {
return false;
} else {
cout << "Invalid selection, please make a valid selection." << endl;
}
}
}
Alight, so by and large this works fine, I'm just having one small problem with my final else statement. As long as the user has entered a type of int, the loop does what it is supposed to, however if any kind of string is entered (i.e. 45r, rts, 3e5) the loop stops taking user input and just spirals infinitely, cout(ing) Invalid selection... and Your choice... over and over again. I think I need to use .ignore() to drop the \n in the case of a string, but I'm not sure of how to do that. Am I on the right track?
Yes, you're on the right track.
cin >> input tries to extract an integer. If this fails no symbols are extracted from cin and the failbit is set. In this case the extraction won't work anymore. You have to ignore the rest of the user input and clear the error bits:
} else {
cout << "Invalid selection, please make a valid selection." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
// numeric_limits<streamsize>::max() returns the maximum size a stream can have,
// see also http://www.cplusplus.com/reference/std/limits/numeric_limits/
}
See also Why is this cin reading jammed?.
Related
I am prompting the user to enter an integer value. When the value is incorrect, the program works. However, when the user enters an integer input, the user needs to enter the input twice.
I looked at other tutorials on how to use the while loop to catch erroneous input, and that part worked for me. However, the integer values need to be entered twice in order for the program to run.
#include <iostream>
using namespace std;
int main() {
cout << "*************************************************" << endl;
cout << "******************|DVD Library|******************" << endl;
cout << "*************************************************" << endl;
cout << "1.\tAdd DVD" << endl;
cout << "2.\tDelete DVD" << endl;
cout << "3.\tSearch DVD" << endl;
cout << "4.\tList All DVDs in the Library" << endl;
cout << "5.\tAdd DVD to Favorites List" << endl;
cout << "6.\tDelete DVD from Favorites List" << endl;
cout << "7.\tSearch DVD in Favorites List" << endl;
cout << "8.\tList All DVDs in Favorites List" << endl;
cout << "9.\tQuit" << endl;
cout << "*************************************************" << endl;
int input;
cin >> input;
while (!(cin >> input)) {
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter an integer --> " << flush;
}
if (input < 1 || input > 9) {
cout << "Invalid input! Please try again!" << endl;
}
return 0;
}
You ask for the input twice:
cin >> input;
while(!(cin >> input )){
Removing the first line might make it work you intended.
'The user has to enter the input twice' Look at your code
int input;
cin >> input;
while(!(cin >> input )){
How many times do you ask the user for input?
You'd have more luck with this
int input;
while(!(cin >> input )){
Your error recovery code looks reasonable, haven't tested it though.
int input;
while (cout << "Your choice: ",
!(cin >> input) || input < 1 || 9 < input)
{
cin.clear();
while (cin.get() != '\n');
cerr << "Invalid input! Please try again!\n";
}
Thanks everyone! The "cin >> input;" line was unnecessary. At first, I left it there because it would actually tell the user the error message if the user entered a numeric input such as a double. So, if the user entered something like 3.3, the program would display an error message that I specified ("Please enter an integer" line). However, the program in this case (when there is a double) asks the user to prompt for the integer input twice and then continues the program. When I delete the said unnecessary line, the program accepts a double input, but what it does, it takes the numeric value before the decimal point and uses it as the integer. So, a value of 1.2 is recorded as 1 when I tested it. I'm unsure why this phenomenon happens, but the program works otherwise. Maybe it accounts for human error?
#include <iostream>
using namespace std;
int main() {
cout << "*************************************************" << endl;
cout << "******************|DVD Library|******************" << endl;
cout << "*************************************************" << endl;
cout << "1.\tAdd DVD" << endl;
cout << "2.\tDelete DVD" << endl;
cout << "3.\tSearch DVD" << endl;
cout << "4.\tList All DVDs in the Library" << endl;
cout << "5.\tAdd DVD to Favorites List" << endl;
cout << "6.\tDelete DVD from Favorites List" << endl;
cout << "7.\tSearch DVD in Favorites List" << endl;
cout << "8.\tList All DVDs in Favorites List" << endl;
cout << "9.\tQuit" << endl;
cout << "*************************************************" << endl;
int input;
while (!(cin >> input)) {
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter an integer --> " << flush;
}
if (input < 1 || input > 9) {
cout << "Invalid input! Please try again!" << endl;
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am having a number of problems in my program that all have to do with input.
The first thing in the program I ask the user to input is their name which I do so with this
cout << "Please tell me your name." << endl;
getline(cin, user_name);
cout << "Hello " << user_name << " and welcome to Fantasy Battle!" << endl;
where user_name is declared as a string variable elsewhere. This part seems to have no problems as the following message displays to the screen correctly
The next input from the user comes from this code
{
cout << "Hello, what would you like to do?" << endl;
cout << "1. Play" << endl << "2. Exit" << endl;
cout << "Please enter the number corresponding to your choice from the list
above." << endl;
for(;;)
{
if(cin >> menuChoice)
{
if(cin.get() == '.')
{
cin.clear();
cin.ignore(10000, '\n');
}
if(menuChoice == 1 || menuChoice == 2)
break;
else
{
cout << "You did not enter a valid menu option. Please try
again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
else
{
cout << "You did not enter a valid menu option. Please try again."
<< endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
if(menuChoice == 2)
{
return 2;
}
else
{
//setup a fight code further down
}
One the first run through if I enter 2 it will exit the program successfully from main or if enter 1 it will run through the fight function. However, if I go through 1 fight and get back the program asking me to either enter 1 or 2 to play or exit, I can enter 2 infinite times and it will not exit the program. I am not sure what it causing this.
for(;;)
{
game = menu();
if(game == 2)
{
break;
}
else
{
fight();
}
}
return 0;
The code inside the menu() function of my program is as follows and is where the rest of the input for my program is contained. I am using getline(cin, fighterName) to get a string from the user to use as a name for each character they want to create
The problem I am having is that it starts to just save the name of characters as empty without asking.
cout << "How many fighters should be on Team 1?" << endl;
//Input Validation
for(;;)
{
if(cin.get() == '.')
{
cin.clear();
cin.ignore(100000, '\n');
}
if(cin >> team1Size)
{
if(team1Size <= 0)
{
cout << "The team must be a size of at least 1 fighter. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
else
{
break;
}
}
else
{
cout << "You did not enter a valid number. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
cout << "How many fighters should be on Team 2?" << endl;
//Input Validation
for(;;)
{
if(cin.get() == '.')
{
cin.clear();
cin.ignore(100000, '\n');
}
if(cin >> team2Size)
{
if(team2Size <= 0)
{
cout << "The team must be a size of at least 1 fighter. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
else
{
break;
}
}
else
{
cout << "You did not enter a valid number. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
//Set up team 1
cout << "Begin setup for team 1:" << endl << endl;
for(int i = 0; i < team1Size; i++)
{
cout << "Which character type should fighter " << i+1 << " be?" << endl;
cout << "1. Barbarian" << endl;
cout << "2. BlueMen" << endl;
cout << "3. Vampire" << endl;
cout << "4. Medusa" << endl;
cout << "5. Harry Potter" << endl;
cout << "Please enter the number corresponding to your choice from the list above." << endl;
for(;;)
{
if(cin.get() == '.')
{
cin.clear();
cin.ignore(100000, '\n');
}
if(cin >> fighterType)
{
if(fighterType < 1 || fighterType > 5)
{
cout << "You did not enter a valid choice. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
else
break;
}
else
{
cout << "You did not enter a valid choice. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
//Now that we have the desired type of the fighter we must add a fighter of the correct type to the linked list
//representing team 1. We will do so by calling the add function of the linked list
cout << "Please enter the name of this fighter." << endl;
getline(cin, fighterName);
if(fighterType == 1)
{
team1.addBack("Barbarian", fighterName);
}
else if(fighterType == 2)
{
team1.addBack("BlueMen", fighterName);
}
else if(fighterType == 3)
{
team1.addBack("Vampire", fighterName);
}
else if(fighterType == 4)
{
team1.addBack("Medusa", fighterName);
}
else
{
team1.addBack("HarryPotter", fighterName);
}
}
cout << "Team 1 has been created!" << endl << endl;
//Set up team 2
cout << "Begin setup for team 2:" << endl << endl;
for(int i = 0; i < team2Size; i++)
{
cout << "Which character type should fighter " << i+1 << " be?" << endl;
cout << "1. Barbarian" << endl;
cout << "2. BlueMen" << endl;
cout << "3. Vampire" << endl;
cout << "4. Medusa" << endl;
cout << "5. Harry Potter" << endl;
cout << "Please enter the number corresponding to your choice from the list above." << endl;
for(;;)
{
if(cin.get() == '.')
{
cin.clear();
cin.ignore(100000, '\n');
}
if(cin >> fighterType)
{
if(fighterType < 1 || fighterType > 5)
{
cout << "You did not enter a valid choice. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
else
break;
}
else
{
cout << "You did not enter a valid choice. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
//Now that we have the desired type of the fighter we must add a fighter of the correct type to the linked list
//representing team 2. We will do so by calling the add function of the linked list
cout << "Please enter the name of this fighter." << endl;
getline(cin, fighterName);
if(fighterType == 1)
{
team2.addBack("Barbarian", fighterName);
}
else if(fighterType == 2)
{
team2.addBack("BlueMen", fighterName);
}
else if(fighterType == 3)
{
team2.addBack("Vampire", fighterName);
}
else if(fighterType == 4)
{
team2.addBack("Medusa", fighterName);
}
else
{
team2.addBack("HarryPotter", fighterName);
}
}
cout << "Team 2 has been created!" << endl << endl;
cout << "Let the fight begin!" << endl << endl;
return 0;
}
The final piece of input from my code is the following which simply asks the user to enter a character either y or n and then executes a function if y is entered.
cout << "Would you like to see the contents of the loserPile?" << endl;
cout << "Please enter y for yes or n for no" << endl;
for(;;)
{
if(cin >> displayLosers)
{
if(displayLosers != 'y' && displayLosers != 'n')
{
cout << "You did not enter either y or n. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
else
break;
}
else
{
cout << "You did not enter either y or n. Please try again." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
if(displayLosers == 'y')
{
losers.displayPile();
}
If someone could point out where I am making the error in obtaining user input I would appreciate it as I am running out of things to try that I know of.
You are creating a lot of problems by adding if(cin.get() == '.')
The >> operator will convert the input string "1." to 1, and if you call ignore(...,'\n') the . and any other characters before \n will be ignored. Test for if(cin >> number){...} is also not necessary. You can initialize the value to -1 to indicate an error:
int menuChoice;
for(;;)
{
menuChoice = -1;
cin >> menuChoice;
cout << menuChoice;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if(menuChoice == 1 || menuChoice == 2)
{
cout << menuChoice << "\n";
break;
}
cout << "You did not enter a valid menu option. Please try again." << endl;
}
Just make sure you are using the right input. For Yes or No option the input should be char:
cout << "enter y or n\n";
for(;;)
{
char val;
cin >> val;
if(val != 'y' && val != 'n')
{
cout << "You did not enter either y or n. Please try again." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else
break;
}
I am a very newbie programmer, so I don't really know much about writing code to protect the application.. Basically, I created a basicMath.h file and created a do while loop to make a very basic console calculator (only two floats are passed through the functions). I use a series of if and else if statements to determine what the users wants to do. (1.add, 2.subtract, 3.multiply, 4.divide) I used a else { cout << "invalid input" << endl;} to protect against any other values, but then I tried to actually write a letter, and the program entered a infinite loop. Is there anyway to protect against users who accidentally hit a character instead of a number?
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
One way would be to use exception handling, but as a newbie you're probably far from learning that.
Instead use the cin.fail() which returns 1 after a bad or unexpected input. Note that you need to clear the "bad" status using cin.clear().
A simple way would be to implement a function:
int GetNumber ()
{
int n;
cin >> n;
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Not a valid number. Please reenter: ";
cin >> n;
}
return n;
}
Now in your main function wherever you are taking input, just call GetNumber and store the returned value in your variable. For example, instead of cin >> numOne;, do numOne = GetNumber();
When you input to cin, it is expecting a specific type, such as an integer. If it receives something that it does not expect, such as a letter, it sets a bad flag.
You can usually catch that by looking for fail, and if you find it, flush your input as well as the bad bit (using clear), and try again.
Read a whole line of text first, then convert the line of text to a number and handle any errors in the string-to-number conversion.
Reading a whole line of text from std::cin is done with the std::getline function (not to be confused with the stream's member function):
std::string line;
std::getline(std::cin, line);
if (!std::cin) {
// some catastrophic failure
}
String-to-number conversion is done with std::istringstream (pre-C++11) or with std::stoi (C++11). Here is the pre-C++11 version:
std::istringstream is(line);
int number = 0;
is >> number;
if (!is) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
} else if (!is.eof()) {
// line is a number, but ends with a non-number, e.g. "123abc",
// whether that's an error depends on your requirements
} else {
// number is OK
}
And here the C++11 version:
try {
std::cout << std::stoi(line) << "\n";
} catch (std::exception const &exc) {
// line is not a number, e.g. "abc" or "abc123", or the number is too big
// to fit in an int, e.g. "11111111111111111111111111111111111"
std::cout << exc.what() << "\n";
}
I'm creating a very simple number guessing game for a school project and am having trouble with the repeating main menu. I created it using a do-while loop and the problem I'm having is that the menu selection variable is an int, and so when I (or the user) enters a non-int input by accident when selecting from the menu the }while(condition) at the end of the main loop can't catch it and the program repeats infinitely. Conversely if you enter an invalid int at menu selection the program catches it displays the "invalid input" message and then repeats the main menu.
It's kind of hard to explain in writing exactly what I mean so here is the source code with relevant lines denoted with an asterisk. I'm saving as .cpp and am compiling in linux using g++ -ansi -pedantic -Wall -Werror The teacher has forbidden hardcoding in conditional statements hence the global constants.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int PLAY = 1, HIGH_SCORE = 2, EXIT = 3;
const char YES = 'y', NO = 'n';
int main()
{
// Randomly generated value
int randomNumber;
// User input
int userGuess, menuChoice;
char repeat;
// Calculated value
int numberOfGuesses;
// Place-holder values (to be replaced by calculated values)
int score1 = 1000, score2 = 2000, score3 = 3000;
cout << endl << endl;
cout << "Greetings! This is a number guessing game where I think of" << endl
<< "a whole number between one and ten and you try to guess it!" << endl
<< "You can guess as many times as you like, so don't be afraid" << endl
<< "to use trial and error, but your score is based on the " << endl
<< "number of guesses you make (the lower the better) so don't " << endl
<< "guess too haphazardly. Remember, only guess whole numbers!" << endl
<< endl;
do
{
cout << endl << "Main menu." << endl
<< "1. Play game" << endl
<< "2. Display high scores" << endl
<< "3. Exit game" << endl
<< "Please select an option: ";
cin >> menuChoice;
if (cin.fail()){
cout << "Please enter a valid choice" << endl;
continue;
}
cin.ignore();
switch(menuChoice)
{
case PLAY:
do
{
unsigned seed = time(0);
srand(seed);
randomNumber = 1 + rand() % 10;
cout << endl << "Press enter when you're ready to begin!";
cin.ignore();
cout << "Ok I thought of one!" << endl << endl;
numberOfGuesses = 0;
do
{
numberOfGuesses++;
cout << "Enter your guess: ";
cin >> userGuess;
cin.ignore();
// Check user's guess
if (userGuess == randomNumber)
cout << "Correct! That was impressive!" << endl << endl;
else if (userGuess < randomNumber)
cout << "Not quite, you guessed low." << endl << endl;
else if (userGuess > randomNumber)
cout << "Not quite, you guessed high." << endl << endl;
}while (userGuess != randomNumber);
cout << "Your score for this game was " << numberOfGuesses << endl;
// Determine if a high score was beaten
if (numberOfGuesses <= score1)
{
score3 = score2;
score2 = score1;
score1 = numberOfGuesses;
cout << "That's a new all time high score!" << endl;
}
else if (numberOfGuesses <= score2)
{
score3 = score2;
score2 = numberOfGuesses;
cout << "That's a new high score!" << endl;
}
else if (numberOfGuesses <= score3)
{
score3 = numberOfGuesses;
cout << "That's a new high score!" << endl;
}
else
{
cout << endl;
}
cout << "Would you like to play again? y/n: ";
cin.get(repeat);
cin.ignore();
while (tolower(repeat) != YES && tolower(repeat) != NO)
{
cout << endl;
cout << "Sorry, that is an invalid choice." << endl
<< "Please enter 'y' for yes or 'n' for no: ";
cin.get(repeat);
cin.ignore();
}
}while (tolower(repeat) == YES);
break;
case HIGH_SCORE:
cout << endl << "High Score 1: " << score1 << endl
<< "High Score 2: " << score2 << endl
<< "High Score 3: " << score3 << endl << endl;
cout << "Press enter to continue. ";
cin.ignore();
break;
case EXIT:
cout << endl << "Thanks for playing, I'll see you next time!" << endl << endl;
break;
default:
cout << endl << "That is an invalid selection, please enter '1', '2' or '3'"
<< endl;
break;
}
}while (menuChoice != EXIT);
return 0;
}
Code Edited in regards to current answer.
Please let me know if you need anymore information, thanks in advanced!
Use cin.fail() like this (instead of just cin >> menuChoice;) (modelled after this post):
cin >> menuChoice;
if (cin.fail()) {
cout << "Please enter a valid choice" << endl;
cin.clear();
cin.ignore();
continue;
}
//Remove the cin.ignore() at this place!
For more detailed info, see this SO thread
Use a do-while to ensure that the loop body will run at least once.
By using a do-while and prompting a user outside the loop you assume the user wants to play the game once which may not be the case.
A cleaner approach IMO would be use a while loop. Display the menu outside the loop and at the end of the loop. The user will have the choice to exit immediately.
cout << "Greetings.....
cout << menu
// Get menuChoice input here.
while(menuChoice != EXIT){
...
cout << menu //reprompt at end to continue or exit cleanly
// Get menuChoice input here
}
Input Validation is a perfect time to use a do-while
do{
if(!cin){
cout << "Invalid input"
cin.clear()
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}while(!(cin >> menuChoice)) // This gets console input. If fail, loop.
Use numeric_limits<streamsize>::max() to completely clear the
buffer.
Use cin.clear() to reset the fail flag on cin so it wont
always be false.
cin.fail() is fine. However some would consider !cin more natural.
i need to prevent the junk left in the buffer as entering a value for a switch case menu from being used in a function called by the menu where their is user input.
menu code
void menu()
{
bool done = false;
string input;
while(!done)
{
cout << "Welcome to the DVD database." << endl;
cout << "1. Add A DVD" << endl;
cout << "2. Delete a DVD." << endl;
cout << "3. Edit a DVD." << endl;
cout << "4. List By Category." << endl;
cout << "5. Retrieve by a DVD by Title." << endl;
cout << "6. Display collection by year" << endl;
cout << "7. Display collection by title" << endl;
cout << "-999. Exit program" << endl;
cout << "Please choose an option by entering the corresponding number" << endl;
cin >> input;
int value = atoi(input.c_str());
switch(value)
{
case 1:addDVD(); break;
case 2:deleteDVD(); break;
// case 3:editDVD(); break;
case 4:listByCategory();break;
case 6:displayByYear();break;
case 7:displayByTitle();break;
case -999: writeToFile(); exit(0); break;
default : cout <<"Invalid entry"<< endl; break;
}
}
}
void retrieveByTitle()
{
string search;
int size = database.size();
int index = 0;
bool found = false;
cin.ignore();
cout << "Please enter the title of the DVD you would like to retrieve: " << endl;
getline(cin,search);
cout << search;
while(!found && index<size)
{
if(database.at(index)->getTitle().compare(search)==0)
{
cout << database.at(index)->toString();
break;
}
}
cout << endl;
}
if 5 is entered in the menu, the program skips the user input in the method
This code works, but it has the same problem you describe if you eliminate the 'cin.ignore()', which removes the extra delimiters ignored by the cin >> operator:
#include <iostream>
#include <climits>
using namespace std;
int main() {
string a, b;
while (true) {
cout << "write 'x' to exit: " << endl;
cin >> a;
if (a == "x") {
break;
}
cout << "read '" << a << "'" << endl;
cout << "now write a line: " << endl;
cin.clear(); // clears cin status
cin.ignore(INT_MAX); // clears existing, unprocessed input
getline(cin, a);
cout << "read '" << a << "'" << endl;
}
return 0;
}
When dealing with interactive user input you should use std::getline()
The std::cin is flushed to the application every time you hit <enter>. So this is the logical junks you should read data from the user in.
std::string answer;
std::cout << "Question:\n";
std::getline(std::cin, answer);
This gets you everything the user provided in response to the previous question.
Once you have the input you should get the value you think is on the input. Once you have this you should check if there is any other junk on the input (if there is then abort and re-try) otherwise validate the data you expected.
If you were expected an integer;
std::stringstream linestream(answer);
int value;
std::string junk;
if ((answer >> value)) && (!(answer >> junk)))
{
// If you got data
// and there was no junk on the line you are now good to go
}
In your specific example there is already a simple way to do this:
std::getline(std::cin, input);
int value = boost::lexical_cast<int>(input); // throws an exception if there is not
// an int on the input (with no junk)