Title Description:
Enter a string representing an integer to convert the string to an integer and output. For example, the input string "345", the output integer 345.
Program code:
#include <gtest/gtest.h>using namespacestd;intStrtoint (Const Char* Szvalue,intNbase =0,BOOL* Bvalid =NULL) { Long LongNvalue =0; intNsign =1; if(bvalid) {*bvalid =false; } if(!szvalue) { return 0; } if(Nbase <0|| Nbase = =1|| Nbase > $) { return 0; } CharCData = *szvalue++; while(CData <=' ')//Skip Whitespace{cData= *szvalue++; } if(CData = ='+') {CData= *szvalue++; } Else if(CData = ='-') {CData= *szvalue++; Nsign= -1; } if(nbase==0) { if(CData! ='0') Nbase=Ten; Else if(*szvalue = ='x'|| *szvalue = ='X') Nbase= -; ElseNbase=8; } if(Nbase = = -) { if(CData = ='0'&& (*szvalue = ='x'|| *szvalue = ='X') ) {Szvalue++; CData= *szvalue++; } } while(CData! =' /') { intNdata =0; if(CData >='0'&& CData <='9') {Ndata= cdata-'0'; } Else if(CData >='A'&& CData <='Z') {Ndata= CData-'A'+Ten; } Else if(CData >='a'&& CData <='Z') {Ndata= CData-'a'+Ten; } Else { Break; } if(Ndata >= nbase)//Bad Digit { Break; } nvalue= (Nbase * nvalue) +Ndata; if(Nvalue > std::numeric_limits<int>:: Max ()) {Nvalue=0; Break; } cData= *szvalue++; } if(bvalid) {*bvalid = (CData = =' /'); } return(int) (Nsign *nvalue);} TEST (Pratices, tstrtoint) {//NULL-0//", 0//"0"-0//"+123"-123//" -123"- -123//"123", 123assert_eq (Strtoint (NULL),0); Assert_eq (Strtoint (""),0); Assert_eq (Strtoint ("0"),0); Assert_eq (Strtoint ("+123"),123); Assert_eq (Strtoint ("-123"), -123); Assert_eq (Strtoint ("123"),123); //16 binary//0x10//0x0-0//0x123-291Assert_eq (Strtoint ("0x10"), -); Assert_eq (Strtoint ("0x10", -), -); Assert_eq (Strtoint ("0x0", -),0); Assert_eq (Strtoint ("-0x123"), -291); //8 binary//010-8//0123Assert_eq (Strtoint ("010"),8); Assert_eq (Strtoint ("0123",8), the);}
[Algorithm practice] Converts a string to an integer