TA的每日心情 | 慵懒 2016-4-21 12:07 |
---|
签到天数: 3 天 连续签到: 1 天 [LV.2]偶尔看看I 累计签到:3 天 连续签到:1 天
|
马上加入,结交更多好友,共享更多资料,让你轻松玩转电力研学社区!
您需要 登录 才可以下载或查看,没有账号?立即加入
×
本函数my_atoi与C标准库函数atoi相同,测试代码中与atoi比较输出结果。
" c1 C5 _/ y' t! k# Q#include <iostream>: s7 e3 H, C' E( @0 D8 \
#include <cstdlib>4 {- \* U) {7 C7 R/ S' Q
#include <string>7 o5 h1 x* M% G/ r# }/ b" a( B1 F2 l/ C
#include <stdlib.h>3 k) i1 d1 H3 p4 S$ c' a; t1 g( A
#include <ctype.h>
0 l3 `, d( {3 w3 o! C$ t, ^% j. [#include <string>
& D c% ?5 |, c. r l! v: G#include <list>8 P- c& p9 A' ]8 D {. h$ S: j, A
using namespace std;$ M6 M; k/ c7 p
// atoi
, R+ Y- ^) o9 W. {3 W/ j1 aint my_atoi ( const char * str )
2 T# _. y4 e6 x* p7 z# r. U{! f Q8 B: N+ {5 C; z2 g$ V$ n# R
int flag = 1; //for minus or positive
6 ?) s9 D2 g0 u' ?- e' ] int result = 0;+ W& i& _4 V8 w' o$ n' B; z
if(str)- ]2 P1 u( ~, f/ a. y6 I
{
. R8 w7 a/ v# i# ]6 T while( *str )" ~& y& ]) {/ B2 d+ g- _
{2 M e1 u8 w7 x, e9 x% Z( Q* T8 X
if(( '-'==*str ) || ( '+'==*str))
4 Z+ a2 G: f$ X0 n8 I% X {
; f+ y. ~) G$ P" y flag = ( '-'==*str ) ? -1 : 1 ;
5 M" w! n( L' Z# {! }4 G0 [+ o while( isspace(*(++str)) );
+ U- [* Z8 U& q5 v# N" w }
" Y& S: i; y) _* {- @) Y2 x* X if( isdigit(*str) )
0 J- S- z2 B5 x6 c {
8 k! w) w" U5 a" Z9 y break;) b1 ]: s' K; H7 @8 ?' U3 I
}
, c# n) o: d( {# \6 H; U7 j str++;0 J* c3 U3 N1 f
}3 @$ u, T$ f; e; P3 a5 g5 Z
if(*str)
$ F% E+ F: w4 }* h9 D. E& J {
- j ^/ ]; m; b. W+ W; `. ^ do{" S0 `/ u% A6 U2 t+ l
result =result * 10 -'0' + *str;
9 v, D: a& O4 \ }while( isdigit(*(++str)) );1 F5 _# }8 K0 ~ L' X
result *= flag;
u! k* l( i1 M! p1 [. r2 [2 X }1 v$ _/ c! _ S: F/ M$ S
}
- D8 g, f z, U# y6 c; v( x! G return result;4 r! X$ V+ a( A
}
, ~- U" {4 \7 F7 _8 pint main(int argc, char *argv[])
$ H+ [) F& _+ l& j5 D8 ^{
[ I: H# Y" Y/ i; Y# q, U# s list<string> li;3 ]$ t! r0 L1 _) Q* S- M- m
li.push_back("0");
/ p$ a. E6 g) o6 w1 D li.push_back("123");
7 T# y3 M# L( J li.push_back("-12");# `5 ~# o, i# x5 [1 J; ?
li.push_back("1 ");; g5 ?( w ^' U: o
li.push_back("1235k344");
0 U5 F: a- b2 n- V9 { li.push_back(" -1234");
: Y1 `7 i' G9 V' A. ] li.push_back(" - 123");
: A2 T4 M. N& }" W li.push_back(" - 1234"); // \t3 B9 _5 p* i/ z& h$ d) w7 P* I( q {; r
li.push_back("1000000000000000000000000000");. ? K; p* v1 _$ r7 A3 K
li.push_back("1a");
# N% r, s: O: \( E# {4 c li.push_back("-");
2 w7 u" ]; ]) K: T7 A; B: Z for(list<string>::iterator it = li.begin(); it != li.end(); it++)6 r! ~$ g* a- ?/ Q1 f: o# a4 t
{
% c6 q( S& ?: T% x cout <<"input = "<<*it & |# [! \7 e6 t: [: z7 ~' X' r
<< ", atio() = " <<atoi(it->c_str()) 7 ]3 M: b8 N H( X# X3 e" d
<<", my_atio() = " << my_atoi(it->c_str())<<endl;* e2 p/ c) O% u/ s
}* B j; Z( k2 `* _1 I. E
return 0;& L2 T+ t2 \) T9 q$ \+ ~
} |
|