Currently writing a switch menu system and I'm looking into validating each input that the user enters against its datatype:
char, string, int, double, float. I've managed to get the int one working but it also allows double and float numbers to be entered. I'm currently trying to get the char one working but I'm having some problems, it works if I enter anything apart from a value between 65 and 121 it obiously accepts that input.
Any help or directions on where to find what I need would be greatly appriciated.
system ("CLS");
int value;
cout << "Enter Your choice:"<< endl;
cout << "1. Integer"<<endl;
cout << "2. Float"<<endl;
cout << "3. Double"<<endl;
cout << "4. Char"<<endl;
cout << "5. String"<<endl;
cin >> value;
switch (value)
{
case 1:
//Prompt the user to enter an integer.
cout << "Enter an integer: ";
cin >>inputIntOne;
//While the input entered is not an integer, prompt the user to enter an integer.
while (!(cin >> inputIntOne))
{
// Explain error
cout << "ERROR: a number must be entered:";
cin.clear();
cin.ignore(132, '\n');
}
break;
insertMenu2();
case 4:
cout << "Enter a char";
cin >> inputCharOne;
while (inputCharOne <65 ||inputCharOne > 122)
{
// Explain error
cout << "ERROR: a Character must be entered:";
cin.clear();
cin.ignore(132, '\n');
}
break;
It gets a bit hairy, depending on how "correct" you want to be.*
But for just basic parsing, you need to receive user input as the "lowest common denominator" of types you want to parse. So in this case, you would need to have the user enter a string, and then you parse that string to see if it matches the criteria of being a floating-point number, then an integer.
#include <iostream>
#include <string>
#include <cctype>
template < typename TYPE > TYPE get_val( constchar* type_str )
{
std::cout << "enter an input of type " << type_str << " and press ENTER: " ;
TYPE value ;
// return valid input of the correct type, immediately followed by a new line
if( std::cin >> value && std::cin.get() == '\n' ) return value ;
// return not executed; input error
std::cout << "invalid input. try again\n" ;
std::cin.clear() ;
std::cin.ignore( 1000, '\n' ) ;
return get_val<TYPE>(type_str) ;
}
// a preprocessor macro to provide a bit of syntactic sugar
// it simply stringifies the name of the type and forwards to our function
#define GET_VAL(type) get_val<type>( #type )
char get_alpha()
{
std::cout << "enter an alpha charecter: " ;
char c ;
// return the char entered if it is an alpha character
if( std::cin >> c && std::isalpha(c) ) return c ;
// return not executed; input error
std::cout << "invalid input. try again\n" ;
return get_alpha() ;
}
int main()
{
constint i = GET_VAL(int) ;
std::cout << i << '\n' ;
constdouble d = GET_VAL(double) ;
std::cout << d << '\n' ;
const std::string str = GET_VAL(std::string) ;
std::cout << str << '\n' ;
constchar a = get_alpha() ;
std::cout << a << '\n' ;
}