TA的每日心情 | 慵懒 2016-4-21 12:07 |
|---|
签到天数: 3 天 连续签到: 1 天 [LV.2]偶尔看看I 累计签到:3 天 连续签到:1 天
|
马上加入,结交更多好友,共享更多资料,让你轻松玩转电力研学社区!
您需要 登录 才可以下载或查看,没有账号?立即加入
×
本函数my_atoi与C标准库函数atoi相同,测试代码中与atoi比较输出结果。
; v' E9 N4 c6 `+ g/ o) k6 \& z#include <iostream>
3 ]+ n% [( U* d: A( M#include <cstdlib>$ h/ I" S, s7 i
#include <string>
! G! \4 U; @. Q2 u) P#include <stdlib.h>
9 g+ `; Q" b& a9 w9 m: I7 H#include <ctype.h>
, U) ]( _8 }# r2 b0 k* t/ @5 H- |* S#include <string>4 O$ a& q& t2 b9 _) u- L
#include <list>+ Z1 Q* b7 n! I. [- r
using namespace std;
+ e. V+ U) g3 z// atoi
3 ]6 e; N: r3 I+ A* ]- P! Dint my_atoi ( const char * str )4 ~1 ^. B D" u, j6 G1 P
{4 P% b5 u2 b- _
int flag = 1; //for minus or positive a! d2 ?* c! O! P _$ L
int result = 0;
0 U0 |0 D& A* X+ p0 M p, N if(str)
! |3 ]* a, c0 m5 ]. O+ b! P1 o {
& @% [( r/ p- {1 A; |( Z: \( m$ z while( *str )
( b8 q( Z0 ~( h0 Q {% w; p2 d0 `5 H% c
if(( '-'==*str ) || ( '+'==*str))5 j$ @$ V+ }% A0 i5 k( |, ^
{1 W V7 ^! y7 o8 d* i+ T
flag = ( '-'==*str ) ? -1 : 1 ;6 L& x, p5 v9 ~/ l4 I4 ]1 c* m) k# F
while( isspace(*(++str)) );+ [& z" g3 J4 T, i6 _! [6 d
}
$ m- c5 ] e% K: b/ e if( isdigit(*str) )
3 x" l: t7 J* m0 B {
' R$ ^) c: h8 `5 k1 L* u2 T break;! C; J5 [- @/ ]1 b
}1 Q& H. f; W0 D0 H4 @: L: }+ m
str++;" w( l! ~$ \ X5 M0 s
}# o) K d4 G8 w. E4 c7 V a9 ]
if(*str)9 t, F4 {4 ?8 v& K
{
, x9 v/ T: a* A do{+ s1 h. ]6 @$ [
result =result * 10 -'0' + *str;
) n# B: q, y3 p$ f% _ L) `, i }while( isdigit(*(++str)) );
3 f0 I6 i, Z; o& H; |0 H; Z result *= flag;3 \, k9 U K" F2 v( P
}
3 v3 v9 Q) V0 v# ^4 x& r! U) c o }% [2 j# ~ @! A+ U
return result; |/ @* Y# j# y9 c0 N
}+ v+ s6 o0 z5 R! {
int main(int argc, char *argv[])
& \4 G9 X1 t, l) Y+ _{
' i( I; x9 g" S5 Z list<string> li;2 Z4 T q. `" [' h+ q, ]0 A/ }0 t
li.push_back("0");6 P! M2 l$ D2 s; ^
li.push_back("123");" G( W# f2 |& P
li.push_back("-12");6 J7 P1 @: [( Z2 G1 ?5 t$ ~/ H
li.push_back("1 ");& s+ [( ] _: p4 j1 ]
li.push_back("1235k344");
) u9 @7 ~3 n2 { li.push_back(" -1234");
0 k- X% w; A* o* ` li.push_back(" - 123");
4 S) @% B L) [: D li.push_back(" - 1234"); // \t. d7 d" F7 }9 J0 L) e
li.push_back("1000000000000000000000000000");
$ r# `. \5 j, K- z li.push_back("1a");
~0 w& ]9 f: D li.push_back("-");
s- J7 |: _2 D9 J `; O. b) f# b for(list<string>::iterator it = li.begin(); it != li.end(); it++)5 `' p- i2 X( a& }4 n
{
+ b9 i& A# o, _3 _9 V cout <<"input = "<<*it 0 z; G* J* \5 g) v' J; A" j
<< ", atio() = " <<atoi(it->c_str())
( z. W% _( k3 |8 P <<", my_atio() = " << my_atoi(it->c_str())<<endl;
* m4 v4 s/ j7 ^6 M' N& p } Z4 v9 ?, q1 u1 }. J: x
return 0;
$ ], X: w8 P3 g} |
|