Atoi converts the struct type into an integer

Source: Internet
Author: User

C language library function name: atoi
Function: converts a string to an integer.
Source: ASCII to integer.
Prototype: int atoi (const char * nptr );
Function Description: nptr string. If the first non-space character exists, and if it is not a number or a plus or minus sign, zero is returned. Otherwise, type conversion is started, the conversion is stopped when a non-Numeric (including the terminator \ 0) character is detected. The integer number is returned.
Header file: # include <stdlib. h>
Program example:
1)
# Include <stdlib. h>
# Include <stdio. h>
Int main (void)
{
Int N;
Char * STR = "12345.67 ";
N = atoi (STR );
Printf ("string = % s integer = % d \ n", STR, N );
Return 0;
}
Execution result:
String = 12345.67 integer = 12345
2)
# Include <stdlib. h>
# Include <stdio. h>
Int main ()
{
Char A [] = "-100 ";
Char B [] = "123 ";
Int c;
C = atoi (a) + atoi (B );
Printf ("c = % d \ n", c );
Return 0;
}
Execution result:
C = 23
Simple implementation of atoi function source code:
# Include <cctype>
Int my_atoi (const char * p ){
Assert (p! = NULL );
Bool neg_flag = false; // symbol mark
Int res = 0; // result
If (p [0] = '+' | p [0] = '-')
Neg_flag = (* p ++! = '+ ');
While (isdigit (* p) res = res * 10 + (* p ++-'0 ');
Return neg_flag? 0-res: res;
}

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.