如何在C和C ++中将char转换为int?
在C语言中,有三种将char类型变量转换为int的方法。这些给出如下-
sscanf()
atoi()
类型转换
这是使用C语言将char转换为int的示例,
示例
#include<stdio.h>
#include<stdlib.h>
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 <iostream>
#include <string>
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
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短