check whether character is digit or alphabet.

i have been given an assignment to check whether a given character is a digit or an alphabet but without using the header file <ctype>.

I tried but can't find a solution. Please help.
Assuming you're using ASCII characters, each digit and alphabet has an integer representation. If you Google for ASCII code you'll see that the lower case characters are numbered sequentially and same for the upper case letters and the digits. You only need to check which range the character you're given falls between to know whether it's a lowercase, uppercase or digit.
Depending on how your school reacts to this (e.g. would they accept the formally correct answer and update the problem?), you could use the two-argument isalpha/isdigit functions defined in the header <locale> instead of their single-argument counterparts from <cctype>/<ctype.h>
It is easy to check whether a character is a digit.

1
2
3
4
inline bool IsDigit( char c ) 
{
   return ( '0' <= c && c <= '9' );
}


To check whether a character is an alpha you should determine which characters are alphas. For example you can define a static array which will contain all symbols that are alphas.

1
2
3
4
5
6
inline bool IsAlpha( char c )
{
   static const char alpha[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

   return ( std:;strchr( alpha, c ) != NULL );
}


If you may use standard function std::toupper you can make array alpha shorter .
Last edited on
closed account (DSLq5Di1)
You could also use the functions from <cctype> without including the header,

1
2
3
extern "C" int isalpha(int);
extern "C" int isdigit(int);
// etc.. 

Though probably not the answer they are looking for. :P
Topic archived. No new replies allowed.