Input Validation for Case Switch statements

When testing our programs, my professor always tells us to input 123abc or ^Z (ctrl + z) or something along those lines.

I understand input validating regular integers, like making sure they're not negative or something simple like that.

I'm getting confused when he throws these inputs with multiple data types in them. What is a good process for validating these kinds of inputs?

All I'd like to do is if it contains more than 1 character (ie. 123abc or 1b or 7m32 etc...) is just display an error message. I only want to accept 1, 2, 3, or 4.

Here's an example of my cin statement and the error check I have so far

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
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

void menu()
{
    cout<<select;
    cin>>m;
            do
            {
                while(m < 1 || m > 4)
		{
                    cout<<ermsg;
		    cin>>m;
		}
		switch(m)
                {
                    case 1:
                        break;
                    etc...
                }
            }while(m != 4);
}                 


Last edited on
closed account (48T7M4Gy)
Try this as a guide:

http://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c

1
2
3
4
5
6
7
8
9
10
11
int taxableIncome; // ***

for (;;) {
    cout << "Please enter in your taxable income: ";
    if (cin >> taxableIncome) { // ***
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear(); // ***
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); // ***
    }
Topic archived. No new replies allowed.