如何在 C 和 C++ 中将 char 转换为 int?
c++programmingserver side programming更新于 2025/4/29 0:22:17
在 C 语言中,有三种方法可以将 char 类型变量转换为 int。具体方法如下 -
sscanf()
atoi()
类型转换
以下是在 C 语言中将 char 转换为 int 的示例,
示例
#include
#include
int main() {
const char *str = "12345";
char c = 's';
int x, y, z;
sscanf(str, "%d", &x); // Using sscanf
printf("\nThe value of x : %d", x);
y = atoi(str); // Using atoi()
printf("\nThe value of y : %d", y);
z = (int)(c); // Using typecasting
printf("\nThe value of z : %d", z);
return 0;
}
输出
输出如下:
The value of x : 12345
The value of y : 12345
The value of z : 115
在 C++ 语言中,有以下两种方法可以将 char 类型变量转换为 int -
stoi()
类型转换
以下是在 C++ 语言中将 char 转换为 int 的示例,
示例
#include
#include
using namespace std;
int main() {
char s1[] = "45";
char c = 's';
int x = stoi(s1);
cout << "The value of x : " << x;
int y = (int)(c);
cout << "\nThe value of y : " << y;
return 0;
}
输出
以下是输出
The value of x : 45
The value of y : 115
相关文章
C++ 中的封装
C++ 中的默认构造函数
C++ 中的析构函数
您认为 C/C++ 中的运算符 < 比 <= 快吗?
C 语言中结构和联合的区别
C++ 中的 expm1()
C 中的错误处理
C++ 中的 delete() 和 free()
C++ 中的 delete() 运算符
在 C++ 中定义静态成员
打印
下一节:C++ 程序实现自平衡二叉搜索树 ❯❮ 上一节:使用集合实现 Dijkstra 算法的 C++ 程序