Home >Backend Development >C#.Net Tutorial >What is the function in C language to convert a string to an integer data type?
The function is: atoi(), which is declared as "int atoi(char *str);". The function of the atoi function is to convert a string into an integer and return it; there is a size limit for the number corresponding to the string input by atoi (related to the size of the int type). If it is too large, an error of -1 may be reported.
#There are two ways to convert a string into an integer in C language.
int i=atoi(str);
or
sscanf(str,"%d" ,&i);
1 Use atoi function.
atoi's function is to convert a string into an integer and return it.
atoi (meaning ascii to integer) is a function that converts a string into an integer and is used in computer programs and office software.
int atoi(const char *nptr) The function will scan the parameter nptr string and skip the preceding whitespace characters (such as spaces, tab indentation), etc. If nptr cannot be converted to int or nptr is an empty string, 0 [1] will be returned.
Special note that this function requires that the converted string be understood as a decimal number. There is a size limit for the number corresponding to the string input by atoi (related to the size of the int type). If it is too large, an error -1 may be reported.
The declaration is
int atoi(char *str);
For example, atoi("1234"); will Returns the integer type 1234.
To call atoi, you need to reference the header file stdio.h
2 Use sscanf.
sscanf is similar to the standard formatted input function scanf, but the source is not standard input, but a string.
Use sscanf to handle more complex strings.
For example, string char * str = "a=1, b=2";
After defining int a, b;
you can use
sscanf(str,"a=%d, b=%d",&a,&b);
to extract the a and b values. After calculation, a=1, b=2.
To use sscanf, you also need to reference the header file stdio.h.
Recommended tutorial: "C Language"
The above is the detailed content of What is the function in C language to convert a string to an integer data type?. For more information, please follow other related articles on the PHP Chinese website!