C programming: How to convert a character to an integer, float in C?
Convert character to integer, float in C.
In C, you can use the atoi() function to convert a string of characters to an integer. Here's an example code snippet:
Code:
# include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "1234";
int x = atoi(str);
printf("The integer value of the string is: %d\n", x);
char str1[] = "*1234";
x = atoi(str1);
printf("The integer value of the string is: %d\n", x);
return 0;
}
Output:
The integer value of the string is: 1234 The integer value of the string is: 0
In the above code, the atoi() function is used to convert the string "1234" to the integer 1234. The function takes a string as input and returns the integer equivalent of the string. If the input string ("*1234") is not a valid integer, the atoi function returns 0.
Code to convert character to float in C:
In C, you can use the atof () function to convert a string of characters to a floating-point value. Here's an example code snippet:
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char char_array1[] = "45.82734";
float float_value = atof(char_array1);
printf("The converted value is: %f\n", float_value);
return 0. ;
}
Output:
The converted value is: 45.827339
In the above code, atof() function is used to convert the character array "char_array1" to a floating-point value "float_value". The function atof() takes a character array as input and returns a floating-point value.
Note that atoi() , atof() functions requires the stdlib.h header file.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/c-snippets/how-to-convert-a-character-to-an-integer-float-in-c.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics