Converts a numeric string to the corresponding digital output (regardless of overflow)

Source: Internet
Author: User

Use C to write a function that converts a numeric string to a corresponding number, regardless of overflow, (e.g. "12.34" to a number: 12.34), considering an exception input


Thinking: Exceptions such as entering subtitles, etc., may also be entered ' + ', '-' and so on,

The procedure is as follows:

#include <stdio.h> #include <stdlib.h> #include <assert.h>double my_atof (const char* &NBSP;STR) {assert (str);d ouble num = 0;int flag = 0;int point = 0; while  (*STR) {int value = 1;if  ('-'  == *str && 0 ==  flag) flag = -1;else if  ('-'  == *str && 1 ==  Flag) flag = -1;else if  ('-'  == *str && -1 == flag) flag = 1;else if  (' + '  == *str && 0 == flag) flag  = 1;if  (*str ==  '. ') &&point == 0) point++;int temp = point;if  ((*str >=  ' 0 ')  &&  (*str <=  ' 9 ')  &&  (0 == point)) num =  10 * num + *str -  ' 0 ';else if  (*str >=  '0 ')  &&  (*str <=  ' 9 ')  &&  (point > 0)) {temp--; while  (temp--) value = value * 10;num = num +  (double) (*str -   ' 0 ')  / value;} str++;if  (point > 0) point++;} if  ( -1 == flag) Num = -num;return num;} Int main () {double n, m;char buffer[256];p rintf ("enter degrees: "); fgets (buffer,  256, stdin); n = my_atof (buffer);p rintf ("the number is: %f \n",  n ); System ("pause"); return 0;}

Please correct me if there is any mistake or consideration.

This article is from the "Sharing Progress" blog, be sure to keep this source http://xmwen1.blog.51cto.com/10730069/1741609

Converts a numeric string to the corresponding digital output (regardless of overflow)

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.