Issue with input validation

In this part of the program, I am asking the user to select an option from the menu. The only acceptable input should be 1, 2, or 3. The validation is working fine... except when the user enters a character that is not a number. For example, if you enter "f", the program spams the validation statement infinitely. How can I make my program handle unexpected input in this way?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Unit 4 Assignment.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;


int main()
{

	double userPackage;
	cout << "\n\t\tWhich package did you purchase? (Please enter 1, 2, or 3)\n"
		<< "1. Package A\n"
		<< "2. Package B\n"
		<< "3. Package C\n\n"
		<< "Please enter your package: ";
	cin >> userPackage;

	while (userPackage != 1 && userPackage != 2 && userPackage != 3)
	{
		cout << "Please enter 1, 2, or 3: ";
		cin >> userPackage;
	}

	int gigs;
	cout << "How many gigabytes were used?";
	cin >> gigs;

	if (userPackage == 1)
		userPackage = 39.99 + (gigs - 4) * 10;
	else if (userPackage == 2)
		userPackage = 59.99 + (gigs - 8) * 5;
	else userPackage = 69.99;
	
	cout << "Your monthly total is: $" << userPackage << endl;

    return 0;
}
You can do this

1
2
3
4
5
6
7
8
int myInt;
std::cin >> myInt;
if(std::cin.fail()) // In abstract, this is basically checking if the previous input matches
{                      // what was suppose to be inputted (i.e. a character input for an int data type)
                        // If it DOES NOT, then perform the following actions...
    std::cin.clear(); // Clear the input stream
    std::cin.ignore(99999, '\n'); // Ignore the rest of the input.
}


Now you need to figure out how to incorporate this into your program.
Last edited on
Can anyone else help me with this?
Have you tried the perfectly good solution that @fiji885 demonstrated for you?
- change your input variable expecting 1, 2 or 3 to an int?
- check the state of the stream for invalid input;
- clear any failed state and remove anything left in the input buffer.
Seems a good solution to me.
Topic archived. No new replies allowed.