To convert an integer to a string, you can use the sprintf function in stdio.h. Some people might mention itoa, but itoa is actually not a C standard library function; it was added by Microsoft.
The prototype for sprintf is:
int sprintf ( char * str, const char * format, ... );The usage is the same as printf. Of course, it can also be used for other types such as double.
Example:
char str[20];
int s = 1000000;
sprintf(str, "%d", s);To convert a string to an integer, you can also use the sscanf function in stdio.h, and stdlib.h also provides atoi and strtol for conversion.
int sscanf ( const char * str, const char * format, ... );
int atoi ( const char * str );
long int strtol ( const char * nptr, char ** endptr, int base);The usage of sscanf and atoi is very simple. It is worth mentioning the strtol function. The first parameter is the source string, the second parameter is used to receive the starting address of the invalid string component, and the third parameter is the numerical base after conversion.
What does the starting address of the invalid string mean? For example, if the value of nptr is "1234f5eg" and base is 10, the value of endptr after calling will point to "f5eg". If the base is 16, then the value of endptr is "g" (f and e are valid hexadecimal characters, but not in decimal). It can be seen that the type of invalid characters is related to the base. Since the value of the pointer needs to be modified, a double pointer is required. In addition, leading and trailing spaces will be ignored, and spaces in the middle will be treated as invalid characters.
Example:
char buf[] = "12435 fawr22g"
char *stop;
printf("%d\n", (int)strtol(buf,&stop,10));
printf("%s\n",stop);The output is:
12435
fawr22gIn addition, here is an implementation of atoi (the atoi in glibc is implemented directly using strtol):
#include <string.h>
#include <ctype.h>
int atoi(const char *s)
{
int sign = (s[0] == '-') ? -1 : 1;
int i, j, res = 0;
int b = 1;
for (j = strlen(s) - 1; j > i; --j) {
b *= 10;
}
for (i = isdigit(s[0]) ? 0 : 1; i < strlen(s); ++i) {
res += (s[i] - '0') * b;
b /= 10;
}
return res;
}
Comments
No comments yet