How to convert characters to numbers in the C language?

In C language, there are several ways to convert characters to numbers:

  1. Converts a string to an integer.
  2. 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;
}
  1. “Read input from string”
  2. 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;
}
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds