Does anyone know how to write a programme that checks if the user's input is a number or is alphabet, I'm new to c++ and am trying to make a programme that does that,
For e.g
A programme which u input a number and the number gets multiplied but i want the programme to know when the user's input is alphabet and prints out a message saying "Only numbers allowed"
If you guys know how to do this please show me, it would be much appreciated👍
Thanks guys
#include <iostream>
#include <string>
#include <cctype>
usingnamespace std;
// Some possible checking functions
template <typename T> bool anything( T value ) { returntrue; }
bool isPositiveInteger( int i ) { return i > 0; }
bool isInRange( double d ) { return d >= -1 && d <= 1; }
bool isUpperCase( char c ) { return isupper( c ); }
bool isLetter( char c ) { return isalpha( c ); }
//======================================================================
template <typename T> T getVal( constchar *prompt, bool (*checker)( T ) = anything )
{
T value;
string rest;
bool ok = false;
cout << prompt;
while ( !ok )
{
ok = ( cin >> value && checker( value ) ); // Check able to read desired type and in suitable range
cin.clear(); // Clear any failed state
getline( cin, rest ); // Get anything else on the line (and clear the line feed)
ok = ( ok && rest.find_first_not_of( " " ) == string::npos ); // Check there is nothing else on the line
if ( !ok ) cout << "Invalid; please re-enter: "; // If invalid, re-enter
}
return value;
}
//======================================================================
int main()
{
int i = getVal<int>( "Please enter an integer: " );
cout << "You entered " << i << "\n\n";
i = getVal<int>( "Please enter a positive integer: ", isPositiveInteger );
cout << "You entered " << i << "\n\n";
double d = getVal<double>( "Please enter a double between -1.0 and 1.0: ", isInRange );
cout << "You entered " << d << "\n\n";
char c = getVal<char>( "Please enter a single upper-case char: ", isUpperCase );
cout << "You entered " << c << "\n\n";
c = getVal<char>( "Please enter a letter: ", isLetter );
cout << "You entered " << c << "\n\n";
}
Please enter an integer: 1f
Invalid; please re-enter: 3 f
Invalid; please re-enter: 3
You entered 3
Please enter a positive integer: -4
Invalid; please re-enter: 4.0
Invalid; please re-enter: 4
You entered 4
Please enter a double between -1.0 and 1.0: 7.5
Invalid; please re-enter: 0.5
You entered 0.5
Please enter a single upper-case char: SS
Invalid; please re-enter: S S
Invalid; please re-enter: S
You entered S
Please enter a letter: &
Invalid; please re-enter: d
You entered d