c/c++ char和int互转

一.加减‘0’法(只支持小于10的数字)

char转int减‘0’:

int a;
char b='2';
a=b-'0';

int转char加‘0’:

int a=2;
char b;
b=a+'0';

二.sprintf函数(支持任何数字,包括小数)

此函数存在于c标准库中,作用为将一个数字转换为char类型的数组,原型:

int sprintf(char *str, const char *format, ...);

返回值为存入char数组的元素个数,str为转换后的char指针,format为...所对应的类型的标志(如:“%d”,“%f”),...为format对应的类型变量,具体使用如下:

char c[10];
int m=20;
sprintf(c,"%d",m);

对于小数只需要将“%d”改为“%f”及其它即可:

char c[10];
int m=20.2;
sprintf(c,"%f",m);

如果不知道format对应的内容应该是什么的,可以参考我的(其实就是printf和scanf函数的输出输入类型):c/c++ printf和scanf函数的输出输入类型-CSDN博客

如有疑问欢迎私信或评论区留言!

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C语言中,将char类型换为int类型有几种方法可以实现。一种方法是使用类型换运算符,如引用和所示。下面是一个示例程序: ```c #include <iostream> using namespace std; int main() { char ch = 'A'; int converted = int(ch); cout << converted; return 0; } ``` 在这个程序中,我们将字符'A'赋值给了变量ch,然后使用`int(ch)`进行类型换。最后,我们将换后的结果打印出来。 另一种方法是使用C++的`stoi()`函数,如引用所示。这个函数可以将字符串换为整数值。下面是一个使用`stoi()`函数将字符换为整数的示例程序: ```c #include <iostream> #include <string> using namespace std; int main() { char s1[] = "45"; int converted = stoi(s1); cout << "The integer value of x: " << converted; return 0; } ``` 在这个程序中,我们将字符串"45"赋值给了字符数组s1,然后使用`stoi()`函数将字符串换为整数。最后,我们将换后的结果打印出来。 可以根据具体的需求选择适合的方法来进行charint换。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C++-容器-string:charint换【Ascii码强int(char);‘0‘为48】【直接换:char - ‘0‘】](https://blog.csdn.net/u013250861/article/details/128414963)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值