How to convert characters into numbers in C language?

In C language, you can convert characters to numbers using the following methods:

  1. By using the ASCII code of characters: Each character has a corresponding ASCII code in the computer, which can be determined by subtracting the character from the character ‘0’ (the ASCII code for the character 0) to get the number represented by the character.
char c = '5';
int num = c - '0'; // 将字符'5'转换为数字5
  1. You can use the standard library function atoi() to convert a string to an integer. Make sure to include the header file stdlib.h.
#include <stdlib.h>

char str[] = "123";
int num = atoi(str); // 将字符串"123"转换为整数123

It’s important to note that all of the above methods involve converting characters to numbers. If you want to convert a string (a sequence of multiple characters) to a number, you can use the second method. For example, the character ‘5’ can be converted to the number 5, and the string “123” can be converted to the number 123.

bannerAds