String to integer

Source: Internet
Author: User
Key Point: various illegal parameters should be taken into account.

Implementation:

/********************************* String to integer by rowandjj2014 /7/15 ***********************************/# include <iostream> # include <stdlib. h> // if this header file is not added, the compilation Error Using namespace STD; int state = 0; // 0 indicates that the string is invalid, 1 stands for normal long str2int (const char * Str) {long num = 0; If (STR = NULL) // enter null {state = 0; return 0 ;} const char * digit = STR; int minius = 0; // 0 indicates a positive number, and 1 indicates a negative number while (* digit = '') // skip spaces {digit ++ ;} if (* digit = '+') {digit ++ ;} Else if (* digit = '-') {minius = 1; digit ++;} If (* digit = '\ 0 ') // only enter + or-{state = 0; return 0;} while (* digit! = '\ 0') {If (* digit> '9' | * digit <'0') // invalid character {state = 0; return 0 ;} state = 1; num = num * 10 + (* digit-'0'); // core code digit ++ ;} // If (* digit> 0x7fffffff | * digit <(signed INT) 0x80000000) {state = 0; return 0;} return minius? (0-num): num;} int main () {long digit; char STR [1000]; char * P = STR; while (CIN> P) {digit = str2int (p); If (State = 0) {cout <"My God \ n ";} else // state = 1 {cout <digit <Endl ;}} return 0 ;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.