atoiおよびitoa関数の内部実装



Internal Implementation Atoi



C言語は、任意のタイプ(整数、長整数、浮動小数点数など)の数値を文字列に変換するいくつかの標準ライブラリ関数を提供します。以下は、itoa()関数を使用して整数を文字列に変換する例です。

Atoiは文字列を整数に変換します
Itoaは整数を文字列に変換します

#include 'stdio.h'#include 'ctype.h'#include 'stdlib.h'/*Converts a character string into an int or long converts a string to an integer */int my_atoi(char s[])s[i]==' -') / / Skip the sign bit i++ for(n=0isdigit(s[i])i++) n=10*n+(s[i]-'0') / / Convert numeric characters into shaped numbers return sign*n/*Converts an int or long into a character string converts an integer to a string */void my_itoa(int n,char s[]){ int i,j,sign if((sign=n)<0) / / record symbol n=-n / / Make n become a positive number i=0 do{ s[i++]=n%10+'0' / / Take a number }while((n/=10)>0) / / Cycle division if(sign<0) s[i++]='-' s[i]='' for(j=i-1j>=0j--) //The generated number is in reverse order, so it is output in reverse order. printf('%c',s[j])}void main(){ int n char str[100] my_itoa(-123,str) printf(' ') printf('%d ',my_atoi('123')) system('pause')}




次に、私の先生である神の人工知能チュートリアルを共有します。ゼロベース!わかりやすい!ユーモラス!黄色の段落も!私たちの人工知能チームにもぜひご参加ください。 https://blog.csdn.net/jiangjunshow