I saw several questions in a forum yesterday. One of them is to convert the decimal string to a number. I can see many people reply with the words "too simple !". After reading the replies from these people, I was wondering, is it really that simple? If exception handling is not required, it is indeed not difficult; If exception handling is required, it is difficult to fully consider the exception.
To fully consider all exceptions, you only need to spend more time on unit test cases.
The following is a function code that converts a decimal string to a number and adds exception handling, but classifies exceptions.
Int dectoint (const char * pcinput)
{
If (null = pcinput)
{
Throw-1;
}
Int iret = 0;
Int isign = 1;
Int iidx = 0;
/* Determine whether the input is negative */
If ('-' = pcinput [0])
{
Isign =-1;
Iidx ++;
} Else if ('+' = pcinput [0]) {
Isign = 1;
Iidx ++;
} Else {}
While (pcinput [iidx])
{
/* Determines whether a single character is a number. If not, an exception is thrown */
Int inum = pcinput [iidx]-'0 ';
If (inum <0) | (inum> 9 ))
{
Throw-1;
}
/* Determine whether to cross the border. If the cross border is exceeded, an exception is thrown */
Int IMAX = ~ (1 <(8 * sizeof (INT)-1 ));
If (IMAX/10 <iret) | (IMAX-(10 * iret) <inum ))
{
Throw-1;
}
Iret = (10 * iret) + inum;
Iidx ++;
}
/* If the string is null, an exception is thrown */
If (0 = iidx)
{
Throw-1;
}
Iret = iret * isign;
Return iret;
}
The unit test cases used are:
"0 ";
"1234 ";
"+ 1234 ";
"-1234 ";
"2147483647"
"-2147483647"
"2147483648"
"-2147483648"
"12k12"
""
Null