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)