1
.設計函數
int atoi(char *s)
。
//atio函數實現,總感覺自己代碼太繁瑣了,by leetaolion@126.com
//atio轉換舉例 "123"->123
//atio轉換舉例 "00123"->123
//atio轉換舉例 " 0 0123"->123
//atio轉換舉例 "+123"->123
//atio轉換舉例 "-123"->-123
//atio轉換舉例 "(+/-)( /e)00123"->0
//atio轉換舉例 "e00123"->0
#include "iostream.h"
#include "ctype.h"
int my_atoi(char *s);
int my_atoi(char *s)
{
?int i=0,j;
?while (s[0]=='0'||s[0]==' ')//過濾首部0和空格
?{
??s++;
?};
?if ( !isdigit(s[0]) )?? //如果第一位不是數字,則可能是符號位
?{
?switch ( s[0] )
??{
??case '+':
??s++;
??while (s[0]>='0'&&s[0]<='9')
??{
???j=int(s[0]-'0');
???i=i*10+j;
???s++;
??}
??return i;
??break;
??case '-':
??s++;
??while (s[0]>='0'&&s[0]<='9')
??{
???j=int(s[0]-'0');
???i=i*10+j;
???s++;
??}
??return 0-i;
??break;
?
??default:
??return i;
??break;?
??}
?}
??while (s[0]>='0'&&s[0]<='9')
??{
???j=int(s[0]-'0');
???i=i*10+j;
???s++;
??}
??return i;
}
void main( void )
{
?char *s=NULL;
?int i;
?s = "?? +123456";
?i = my_atoi( s );
?cout<<i<<endl;
?s = "?? 0-0123456";
?i = my_atoi( s );
?cout<<i<<endl;
?s = "12345e6";
?i = my_atoi( s );
?cout<<i<<endl;
?
}
?
posted on 2006-09-07 16:12
創建更好的解決方案 閱讀(419)
評論(0) 編輯 收藏 引用