Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

C++ Input Validation Class

Name: Anonymous 2013-12-20 16:52

I'm learning to program. All of my programs for my assignments are console applications. Sometimes things get fancy with fstream and text files, but I'm doing beginner work.

A lot of my programs ask for user input. Since they're console applications, it's console input. I always have to write a while loop that checks for invalid input and loops until the input is valid. What a pain!

So I want to write an input class. The class will have virtual functions and use templates. I want to have the function work like this:

InputVal inv; //declaration of instance of InputVal class object "inv"

inv(variable); //variable can be a double or int. later i will add char support to the class. takes variable by reference and a virtual function is chosen based on the variable's type

The virtual function would be so I can have the class appropriately choose its function based on the type of variable passed as a parameter. A template would be so I don't have to write the same function twice for short, double, int, long int, etc. I wonder if I need to use a virtual function AND a template or if I can just use a template...

:)

Name: I am OP 2013-12-20 17:24

#include <iostream>
#include <typeinfo> //for error message in inVal(T)
using namespace std;

/*==========================
sum is a template function that can accept generic types and return
the same type.
===========================*/
template <class T>
T sum(T a, T b) { return a+b; }

/*==========================
inVal accepts generic types by reference and performs input
validation. I often write a function like this in my programs,
so I thought, why not make a template out of it? It works for
doubles and ints.
It doesn't really work for a char. It will run,
but it won't work as intended since anything from keyboard counts
as a char. You could enter "DDDDDDDDDDD" and the program would
just write the first D to the char and leave the other D's in the
input stream.
===========================*/
template <class T>
void inVal(T &input)
{
    cin >> input;
    while(!input)
    {
        cout << "Valid input requires " << typeid(input).name() << endl;
        cin.clear();
        cin.ignore(10,'\n');
        cin >> input;
    }
    return;
}
/*==========================
Main is just for testing the functions I wrote.
Nothing special.
===========================*/
int main()
{
    int a=1,b=3;
    double a1 = 5, b1 = 6;
    char ch;
    cout << sum(a,b);
    cout << endl << sum(a1,b1);
    inVal(a);
    inVal(a1);
    inVal(ch);
    cout << endl << a;
    return 0;
}

Don't change these.
Name: Email:
Entire Thread Thread List