Question: compile a C function that converts a given string to an integer.
[This program is compiled in Dev C ++ 4.9.9.2]
The following program only considers the decimal string.
Int strtoint (char * Str)
{
Int value = 0;
Int Sign = 1;
If (* STR = '-')
{
Sign =-1;
STR ++;
}
While (* Str)
{
Value = value * 10 + * str-'0 ';
STR ++;
}
Return sign * value;
}
Int main ()
{
Printf ("number = % d/N", strtoint ("1234567 "));
Printf ("number = % d/N", strtos ("-1234567 "));
Printf ("number = % d/N", strtoint ("2147483647 "));
Printf ("number = % d/N", strtos ("-2147483647 "));
System ("pause ");
Return 0;
}
The following program considers octal, decimal, and hexadecimal strings.
Int strtoint (char * Str)
{
Int value = 0;
Int Sign = 1;
Int Radix;
If (* STR = '-')
{
Sign =-1;
STR ++;
}
If (* STR = '0' & (* (STR + 1) = 'X' | * (STR + 1) = 'X '))
{
Radix = 16;
STR + = 2;
}
Else if (* STR = '0 ')
{
Radix = 8;
STR ++;
}
Else
Radix = 10;
While (* Str)
{
If (Radix = 16)
{
If (* STR> = '0' & * STR <= '9 ')
Value = value * Radix + * str-'0 ';
Else
Value = value * Radix + (* STR | 0x20)-'A' + 10;
}
Else
Value = value * Radix + * str-'0 ';
STR ++;
}
Return sign * value;
}
Int main ()
{
Printf ("decimal string translation! /N ");
Printf ("/" 1234567/"= % d/N", strtoint ("1234567 "));
Printf ("/"-1234567/"= % d/N", strtoint ("-1234567 "));
Printf ("/" 2147483647/"= % d/N", strtoint ("2147483647 "));
Printf ("/"-2147483647/"= % d/N", strtoint ("-2147483647 "));
Printf ("/nhex string translation! /N ");
Printf ("/" 0x200/"= % d/N", strtoint ("0x200 "));
Printf ("/"-0x200/"= % d/N", strtoint ("-0x200 "));
Printf ("/" 0x7fffffff/"= % d/N", strtoint ("0x7fffffff "));
Printf ("/"-0x7fffffff/"= % d/N", strtoint ("-0x7fffffff "));
Printf ("/noctal string translation! /N ");
Printf ("/" 0123/"= % d/N", strtoint ("0123 "));
Printf ("/"-0123/"= % d/N", strtoint ("-0123 "));
System ("pause ");
Return 0;
}