Explain String Conversion in C
There are a few functions that exist to convert strings to integer, long integer and float values. They are:
double atof(char *string) -- Convert string to floating point value.
int atoi(char *string) -- Convert string to an integer value
int atol(char *string) -- Convert string to a long integer value.
double strtod(char *string, char *endptr) -- Convert string to a floating point value.
long strtol(char *string, char *endptr, int radix) -- Convert string to a long integer using a given radix.
unsigned long strtoul(char *string, char *endptr, int radix) -- Convert string to unsigned long.
Most of these are fairly straightforward to use. For example:
char *str1 = "100";
char *str2 = "55.444";
char *str3 = " 1234";
char *str4 = "123four";
char *str5 = "invalid123";
int i;
float f;
i = atoi(str1); /* i = 100 */
f = atof(str2); /* f = 55.44 */
i = atoi(str3); /* i = 1234 */
i = atoi(str4); /* i = 123 */
i = atoi(str5); /* i = 0 */
Note:
• Leading blank characters are skipped.
• Trailing illegal characters are ignored.
• If conversion cannot be made zero is returned and errno (See Chapter 17) is set with the value ERANGE.