TA的每日心情 | 慵懒 2016-4-21 12:07 |
|---|
签到天数: 3 天 连续签到: 1 天 [LV.2]偶尔看看I 累计签到:3 天 连续签到:1 天
|
马上加入,结交更多好友,共享更多资料,让你轻松玩转电力研学社区!
您需要 登录 才可以下载或查看,没有账号?立即加入
×
本函数my_atoi与C标准库函数atoi相同,测试代码中与atoi比较输出结果。
: n& ~; J. i) w#include <iostream>
0 C1 ^& |- {4 Z7 G; }2 d#include <cstdlib>% P" V3 _2 f% Y
#include <string>, _8 b- Q, F7 r
#include <stdlib.h>
# n+ @; V+ V* H, A; L! j#include <ctype.h>
8 ?* X/ X# T2 E3 _% Y. S8 I#include <string>
) C" e E9 J* V. i" ^#include <list>4 g7 N7 j& C) s) K( Q5 [9 h' _5 O
using namespace std;
- F: P- O2 v; ?. T// atoi) h" u- F$ |' M( f" e$ t+ M& b
int my_atoi ( const char * str )7 R4 G- d; g( U, h. O3 j0 l
{
$ ^+ m, Y' t) x; {% ^" Q! p. d/ ?7 E int flag = 1; //for minus or positive
% w* P$ r. U8 D int result = 0;
4 W" y8 F+ A. ~$ R$ e: f if(str)( v% I5 T5 \/ d
{; _& z7 f, F7 c
while( *str )
! p/ g6 u" g, |9 b- M {
- [$ M/ c. e9 x8 i$ b8 v if(( '-'==*str ) || ( '+'==*str)). c% r4 F1 t; X7 d) w; V0 y5 Q
{
C' m5 j/ @4 z; ]& x$ k! `3 Y+ d+ Y flag = ( '-'==*str ) ? -1 : 1 ;
* h. g# p1 r0 q0 ^( }! U+ R& t( ? while( isspace(*(++str)) );
[; I# X- o8 F- L }( s7 K! }# e+ V7 P+ s
if( isdigit(*str) )
6 ~: H! F1 ~1 z/ y+ D) v& U9 P" j {
& n- `9 n. Y& `2 C e, n. E break;
3 i) N* X# |0 c, Y }% r& G; n; N- O/ |0 m
str++;" V% p2 ~; q* M; z+ Y7 e
}- ^9 c$ L: l8 J; Z* y+ F8 q
if(*str)
* \' n1 q6 h3 v* [% B; t {/ Z& ]7 F$ B5 h* V7 K, q
do{
% C4 D9 }: s& A! t d9 }* U result =result * 10 -'0' + *str;9 V S% H9 J2 `& j' ~
}while( isdigit(*(++str)) );
" A( M7 L( M9 P result *= flag;( I- U1 U8 H$ e6 s k
}% }' S9 l T3 {/ ~: `
}( N" t: X- g+ a4 V! {' a
return result;
* J( C. ~( j4 ?" Q% c: Y6 k}: F+ U- y: `6 [" X$ I
int main(int argc, char *argv[])/ E& A! Q/ T4 @# r" G" o
{9 m# J( {( Y9 d7 ]. y1 M6 C# w( v
list<string> li;5 U; p$ l. |9 o* t% e& f; |% |9 a g& C
li.push_back("0");
) j8 [6 Z/ R) f li.push_back("123");
4 }3 h3 N5 M* ?+ C li.push_back("-12");0 b$ K3 b$ n% z, f0 S
li.push_back("1 ");6 M) E! ]% K, @, c# T* m8 P( e
li.push_back("1235k344");
1 F1 k; ~. d: x li.push_back(" -1234");+ i4 n$ Y, J" A, n/ z
li.push_back(" - 123");# l8 y/ ]+ B- N0 F6 P
li.push_back(" - 1234"); // \t
9 M7 M, |1 ?! V1 I, l$ e li.push_back("1000000000000000000000000000");
5 z4 L; [. n4 |9 D J+ ^2 N li.push_back("1a");4 M- @1 k! G$ g# \
li.push_back("-");
7 t/ i L' R0 `7 q+ D: j2 U for(list<string>::iterator it = li.begin(); it != li.end(); it++)7 k$ v+ W; X; [
{
: s, N# a. O1 _7 K0 @7 ? cout <<"input = "<<*it # M0 m8 D- A8 j4 w
<< ", atio() = " <<atoi(it->c_str())
+ c4 O3 e3 l" O# s- U8 | <<", my_atio() = " << my_atoi(it->c_str())<<endl;
3 d# u3 M$ Z4 s3 b( ], A4 [7 N }/ Y& U& k* p7 t5 m" ?3 j
return 0;
5 L0 n2 V/ N8 h6 k} |
|