Converts a decimal string to a number.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.