Converting a string to an integer problem (c + +)

Source: Internet
Author: User



1. Converting a string to an integer problem (C + +)

Follow the atoi implementation code:

//follow the Atoi function to convert the string into shaping data asked                    Title//#include "stdafx.h" enum Myenum{evalid = 0,//legal unvalid//illegal};int mstate = evalid;//Define a global variable, set the global variable when the input is not valid; It is possible to determine whether the input is valid by checking the global variable,//implementing string conversion to shaping data atoi problem int strtoint (char* str) {//variable initialization int number = 0;mstate = unvalid;//Judging string is No null if (str! = nullptr) {/******** Determines whether the character is legitimate *********///first determine whether the first bit is "+" or "-" bool minus = false;//positive and negative sign if (*str = = ' + ') {++str;} else if (*str = = '-') {++str;minus = true;} If both are not, then the ++str;/********* processing character conversion is not performed **********///determine if it is a valid character while ((*str >= ' 0 ') && (*str <= ' 9 ')) {number = Number * + (*STR-' 0 '); ++str;} Determine if the normal loop is complete if (*str = = ' + ') {//processing data Mstate = Evalid;if (minus) {number = 0-number;//converted to negative}}else//String error condition {number = 0;}} return number;} int _tmain (int argc, _tchar* argv[]) {//Test printf ("%d\n", Strtoint ("+23"));p rintf ("%d\n", Strtoint (" -23"));p rintf ("%d\ N ", Strtoint (" ")");p rintf ("%d\n", Strtoint ("A23")); return 0;} 

Converting a string to an integer problem (c + +)

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.