TA的每日心情 | 慵懒 2016-4-21 12:07 |
|---|
签到天数: 3 天 连续签到: 1 天 [LV.2]偶尔看看I 累计签到:3 天 连续签到:1 天
|
|
马上加入,结交更多好友,共享更多资料,让你轻松玩转电力研学社区!
您需要 登录 才可以下载或查看,没有账号?立即加入
×
本函数my_atoi与C标准库函数atoi相同,测试代码中与atoi比较输出结果。
6 L# {( d' n4 S- C- A2 H#include <iostream>
1 g F' {4 x; U#include <cstdlib>, y# H! I' S0 j @. l" D
#include <string>" ^4 E4 i5 E7 K" A
#include <stdlib.h>3 [9 x# Y3 N8 {9 k
#include <ctype.h>) ^6 H- o- f9 M$ X9 l
#include <string>
" v% S1 |" w3 W# s6 ?3 ~#include <list>5 o( s }& g! l, D; [% R
using namespace std;0 G1 K' Q" j9 m- f1 l! s! g
// atoi
$ R: k: \( K) Z' qint my_atoi ( const char * str )
8 X# W3 I% J! a G{" `4 I" I# W7 X3 }3 ^' \0 R
int flag = 1; //for minus or positive
% B3 _: B% y- n; E; z int result = 0;
& j- o2 [8 K1 B" i: Q if(str)
9 a& L: m; ^$ S: y {5 m, K3 ~! B7 n2 f
while( *str )3 D$ `& D8 ^* `; y
{- E0 G/ G, N1 T! ]9 W
if(( '-'==*str ) || ( '+'==*str)). {- K1 s/ h% j/ k
{
, t' y, T5 \5 t flag = ( '-'==*str ) ? -1 : 1 ;
. S4 D9 G2 _* e9 R% m while( isspace(*(++str)) );
4 B& m( E/ ~/ j' s' K7 M }! o9 v3 Z; s# a+ B; d4 j/ _3 o
if( isdigit(*str) )
8 K n- J" h. L. t, s5 A2 X {
/ d/ F4 l2 K$ S( O& V W6 w break;
" C8 w# W8 g) A8 b/ C5 m* k( U! s }
+ p8 S1 |+ v" x% g, Q% o5 Y str++;
, ]# ^! Q& {0 q. e- Z6 X1 R% k }
- i, ^* C' D6 u1 j$ Z7 V3 X if(*str)3 l! K% v, h4 h4 }- P+ D' d
{
& o8 s6 C( D( T0 M% c, C% h do{; E- B1 r' B0 e; D% V8 ]
result =result * 10 -'0' + *str;- e$ i+ Y! S# v& R; M2 F* ` Y5 i a* J; M
}while( isdigit(*(++str)) );
# y1 t5 Z% h2 l- r result *= flag;- o* _5 U" E4 z- z; s: c1 V
}
# q" j j% m/ T. N }4 D1 w' N# I# |1 i5 Q5 O, @
return result;' W- w3 [, O0 @8 N
}
. N O3 E3 R) C+ ~/ ?% Lint main(int argc, char *argv[])0 E; B: X) q1 H2 E9 W8 k
{
4 K& w6 ?, w+ q! T! M list<string> li;( i7 {' L Q/ O
li.push_back("0");
; b: ?( W+ k! m/ I- M( ?; B li.push_back("123");, I( c& S! A' i* s) d3 |
li.push_back("-12");
3 a# e- C! T7 C4 _ li.push_back("1 ");
j4 C2 j% Q+ X7 `$ ] li.push_back("1235k344");
% g5 D" K2 i7 h: K& m li.push_back(" -1234");5 D+ J; h( M1 R7 {- a9 W/ r0 ]
li.push_back(" - 123");
* ~2 T9 j) b( P* o li.push_back(" - 1234"); // \t# L/ }; H0 K7 O6 ]+ a
li.push_back("1000000000000000000000000000");
; b2 L2 P8 {! z- _ li.push_back("1a");
+ B' ^) r6 F5 p li.push_back("-");) P4 E& w4 T1 N$ O3 |6 a) B! \- V
for(list<string>::iterator it = li.begin(); it != li.end(); it++)& O! `) c2 ~4 S* A* }7 u2 E
{
0 @2 b- D' M4 a, {) H" }4 ] cout <<"input = "<<*it
4 g( n6 Z/ R0 F* N0 L( B << ", atio() = " <<atoi(it->c_str()) # H0 }; e h: f& m3 i& c( }
<<", my_atio() = " << my_atoi(it->c_str())<<endl;; y- Z4 d# G8 l- i! T
}
* t& ? Y. ?7 W$ d% A6 H9 { return 0;& A4 U W, f) X
} |
|