The string is converted to an integer "123"->123
Topic Description Narration:
Enter a string that consists of numbers. Convert it to an integer and output it.
For example: Enter the string "123". Output integer 123.
A given function prototype int StrToInt(const char *str)
. Implements the ability to convert strings into integers. You cannot use the library function atoi.
Topic Analysis:
To correctly convert a string to an integer step
① when scanning the first character ' 1 ', because it is the first digit. So get the number 1 straight.
② when scanning a second character ' 2 ',1*10+2 = 12
③ continues to scan the characters ' 3 ' when12*10+3=123
So that'sn = n * 10 + c;
Easy to fault:
1) cannot be a null pointer. Otherwise the program crashes when you visit a null pointerif(str == NULL)return 0;
2) to consider positive and negative signs增加sign标记
3) to consider illegal characters. Like a space or something.while(isspace(*str)) ++str 还须要检測当为数字时,我们才開始转化
4) Overflow of integral type. Suppose you enter a very long, very long string, which may be an overflow of integer type方法一、能够将n定义为long long型;方法二、利用定义MAX_INT 和 MIN_INT(对0右移取反),通过比較n和MAX_INT/10的大小
<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<<<<<<<<<<<<<<<<
Reference Code:
intStrtoint (Const Char*STR) {//Pair 0 reverse and move right one Static Const intMax_int = (int)((unsigned)~0>>1);Static Const intMin_int =-(int)((unsigned)~0>>1)-1;unsigned intn =0;//Infer whether it is empty if(str = = NULL)return 0;//Handling spaces while(isspace(*STR)) ++STR;//processing plus/minus intSign =1;if(*str = =' + '|| *str = ='-') {if(*str = ='-') Sign =-1; ++STR; }//Determine the number before you start the conversion while(IsDigit(*STR)) {//Handling overflow intc = *str-' 0 ';if(Sign >0&& (n > max_int/Ten|| (n = = max_int/Ten&& C > max_int%Ten)) {n = max_int; Break; }Else if(Sign <0&& (n > (unsigned) min_int/Ten|| (n = = (unsigned) min_int/Ten&& C > (unsigned) min_int%Ten)) {N = Min_int; Break; } n = n *Ten+ C; ++STR; }returnSign >0?
n : -n;}
The string is converted to an integer "123"->123