1、 C 中将 char 转换为 int
在 C 中,char 类型通常用于存储单个字符,可以隐式地转换为 int。这种转换会给出字符的 ASCII(或 Unicode)值。如有字符 'A',它会被转换为对应的 ASCII 值 65。
#include <stdio.h>
int main() {
    char ch = 'A';
    int num = ch;  // 从 char 到 int 的隐式转换
    printf("字符 '%c' 的整数值是 %d\n", ch, num);  // 输出: 65
    return 0;
}
2、使用 atoi() 将字符字符串转换为整数
如想将一串字符(例如 "123")转换为整数,可以使用 stdlib.h 库中的 atoi() 函数。
#include <stdio.h>
#include <stdlib.h>
int main() {
    char str[] = "123";
    int num = atoi(str);  // 将字符串 "123" 转换为整数 123
    printf("字符串 \"%s\" 的整数值是 %d\n", str, num);  // 输出: 123
    return 0;
}
3、 使用 ASCII 值将 char 转换为 int
如想得到字符本身的数值(即它的 ASCII 值),可以简单地将 char 用在算术运算中。如减去字符 '0' 可以得到相应的整数值。
#include <stdio.h>
int main() {
    char digit = '5';
    int num = digit - '0';  // 将字符 '5' 转换为整数 5
    printf("字符 '%c' 的整数值是 %d\n", digit, num);  // 输出: 5
    return 0;
}
4、C++ 中将单个 char 转换为 int
 C++ 中,方法与 C 几乎相同。如处理的是单个字符,可以直接将 char 类型赋给 int 变量,它会给出字符的 ASCII 值。
#include<iostream>
using namespace std;
int main() {
    char ch = 'A';
    int num = ch;  // 从 char 到 int 的隐式转换
    cout << "字符 '" << ch << "' 的整数值是 " << num << endl;  // 输出: 65
    return 0;
}5、字符数组到整数的转换
有时可能需要将一个字符数组(例如一个表示数字的字符串)转换为整数。在这种情况下,可以使用标准库函数 atoi 或 C++11 的 std::stoi。
1)使用atoi
#include <iostream>
#include <cstdlib>  // for atoi
using namespace std;
int main() {
    const char* str = "1234";  // 字符串 "1234"
    
    // 使用 atoi 将字符数组转换为整数
    int number = atoi(str);
    
    cout << "The integer value is: " << number << endl;
    return 0;
}2)使用stoi
#include <iostream>
#include <string>  // for stoi
using namespace std;
int main() {
    string str = "5678";  // 字符串 "5678"
    
    // 使用 std::stoi 将字符串转换为整数
    int number = stoi(str);
    
    cout << "The integer value is: " << number << endl;
    return 0;
}6、常见错误和注意事项
如果字符表示的是非数字字符(如字母或符号),直接减去 '0' 可能导致意外结果。在此情况下,最好检查字符是否是合法数字字符。atoi 和 std::stoi:这些函数假定输入字符串能够正确表示一个整数。如果字符串包含无效字符(如字母或符号),atoi 会返回 0,std::stoi 会抛出异常(std::invalid_argument 或 std::out_of_range)。
#include <iostream>
#include <string>  // for stoi
using namespace std;
int main() {
    char ch = 'a';  // 非数字字符
    // 判断字符是否是数字
    if (ch >= '0' && ch <= '9') {
        int number = ch - '0';
        cout << "The integer value is: " << number << endl;
    } else {
        cout << "Invalid character for conversion!" << endl;
    }
    return 0;
}