How to convert characters to numbers in the C language?
In C language, there are several ways to convert characters to numbers:
- Converts a string to an integer.
- Include the standard library header file
.
#include <stdio.h>
#include <stdlib.h>
int main() {
char c = '5';
int num = atoi(&c);
printf("%d\n", num); // 输出:5
return 0;
}
- “Read input from string”
- The header file stdio.h.
#include <stdio.h>
int main() {
char c = '7';
int num;
sscanf(&c, "%d", &num);
printf("%d\n", num); // 输出:7
return 0;
}
- Converting with ASCII values: Subtracting the ASCII value of the character ‘0’ from the ASCII value of the character itself will give you the corresponding number.
#include <stdio.h>
int main() {
char c = '9';
int num = c - '0';
printf("%d\n", num); // 输出:9
return 0;
}
The methods above are commonly used for converting characters to numbers, and the specific method used depends on the actual requirements and personal preferences.