Convert a string to an integer:
Bool isdigit (char C)
{
Return (C> = '0') & (c <= '9 ');
}
Bool isalpha (char C)
{
Return (C> = 'A') & (c <= 'Z') | (C> = 'A ') & (c <= 'Z '));
}
Bool isalphaordigit (char C)
{
Return (isdigit (c) | isalpha (c ));
}
Unsigned long str2int (const char * Source, unsigned long & Base)
{
Unsigned long result = 0;
Unsigned long value = 0;
Const char * temp = source;
Base = 10;
// Check whether is valid
If (isalphaordigit (* temp ))
{
// Check the type
If (* temp = '0 ')
{
If (temp [1] = 'X') | (temp [1] = 'X '))
{
Base = 16;
Temp + = 2;
} Else {
Base = 8;
Temp ++;
}
}
While (isalphaordigit (* temp ))
{
Value = isdigit (* temp )? * Temp-'0': * temp-'A' + 10;
Result = Result * base + value;
++ Temp;
}
If (* temp! = '/0 ')
{
// Error
STD: cout <"not valid string" <STD: Endl;
Return-1;
}
Return result;
} Else {
// Error, not Valid String
STD: cout <"not valid string" <STD: Endl;
Return-1;
}
}
Long str2int_signed (const char * Source, unsigned long & Base)
{
If (* Source = '-')
Return-str2int (source + 1, base );
Return str2int (source, base );
}
The Code has been tested and run.